dio官方文档地址,介绍使用很全,Cookie、Log、Interceptor等。而且迭代很快,要时刻关注着,有一些新的适合自己项目的调整,随时加进来。点击传送)
整理的flutter的各类组件的使用demo,一起学习
https://github.com/ZHBoy/FlutterProject01
DioManager网络请求主类
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import '../base/GlobalConfig.dart';
import 'ResultCode.dart';
/*
* 网络请求管理类
*/
class DioManager {
//写一个单例
//在 Dart 里,带下划线开头的变量是私有变量
static DioManager _instance;
static DioManager getInstance() {
if (_instance == null) {
_instance = DioManager();
}
return _instance;
}
Dio dio = new Dio();
DioManager() {
// Set default configs
dio.options.headers = {
"version": '2.0.9',
};
dio.options.baseUrl = "https://cadfen-test.ym.net";
dio.options.connectTimeout = 5000;
dio.options.receiveTimeout = 3000;
dio.interceptors
.add(LogInterceptor(responseBody: GlobalConfig.isDebug)); //是否开启请求日志
dio.interceptors.add(CookieManager(CookieJar())); //缓存相关类
}
//get请求
get(String url, Map params, Function successCallBack,
Function errorCallBack) async {
_requstHttp(url, successCallBack, 'get', params, errorCallBack);
}
//post请求
post(String url, params, Function successCallBack,
Function errorCallBack) async {
_requstHttp(url, successCallBack, "post", params, errorCallBack);
}
_requstHttp(String url, Function successCallBack,
[String method, params, Function errorCallBack]) async {
Response response;
try {
if (method == 'get') {
if (params != null && params.length > 0) {
response = await dio.get(url, queryParameters: params);
} else {
response = await dio.get(url);
}
} else if (method == 'post') {
if (params != null && params.length > 0) {
response = await dio.post(url, data: params);
} else {
response = await dio.post(url);
}
}
} on DioError catch (error) {
// 请求错误处理
Response errorResponse;
if (error.response != null) {
errorResponse = error.response;
} else {
errorResponse = new Response(statusCode: 666);
}
// 请求超时
if (error.type == DioErrorType.CONNECT_TIMEOUT) {
errorResponse.statusCode = ResultCode.CONNECT_TIMEOUT;
}
// 一般服务器错误
else if (error.type == DioErrorType.RECEIVE_TIMEOUT) {
errorResponse.statusCode = ResultCode.RECEIVE_TIMEOUT;
}
// debug模式才打印
if (GlobalConfig.isDebug) {
print('请求异常: ' + error.toString());
print('请求异常url: ' + url);
print('请求头: ' + dio.options.headers.toString());
print('method: ' + dio.options.method);
}
_error(errorCallBack, error.message);
return '';
}
// debug模式打印相关数据
if (GlobalConfig.isDebug) {
print('请求url: ' + url);
print('请求头: ' + dio.options.headers.toString());
if (params != null) {
print('请求参数: ' + params.toString());
}
if (response != null) {
print('返回参数: ' + response.toString());
}
}
String dataStr = json.encode(response.data);
Map<String, dynamic> dataMap = json.decode(dataStr);
if (dataMap == null || dataMap['state'] == 0) {
_error(
errorCallBack,
'错误码:' +
dataMap['errorCode'].toString() +
',' +
response.data.toString());
} else if (successCallBack != null) {
successCallBack(dataMap);
}
}
_error(Function errorCallBack, String error) {
if (errorCallBack != null) {
errorCallBack(error);
}
}
}
dio网络请求失败的回调错误码
/*
* dio网络请求失败的回调错误码
*/
class ResultCode {
//正常返回是1
static const SUCCESS = 1;
//异常返回是0
static const ERROR = 0;
/// When opening url timeout, it occurs.
static const CONNECT_TIMEOUT = -1;
///It occurs when receiving timeout.
static const RECEIVE_TIMEOUT = -2;
/// When the server response, but with a incorrect status, such as 404, 503...
static const RESPONSE = -3;
/// When the request is cancelled, dio will throw a error with this type.
static const CANCEL = -4;
/// read the DioError.error if it is not null.
static const DEFAULT = -5;
}
工程配置文件,用于设置debug开关、日夜模式切换、默认字体等等
import 'package:flutter/material.dart';
/*
*系统主题设置,包括系统默认字体 背景色等
*/
class GlobalConfig {
static bool isDebug = true;//是否是调试模式
static bool dark = false;
static Color fontColor = Colors.black54;
}
**网络请求使用示例 **
import 'package:demo001/data/HotSaleBean.dart';
import 'package:demo001/data/OnlyDataBean.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../widgets/BaseThemeBar.dart';
import '../dio/DioManager.dart';
/*
* 网络Dio库的使用
*/
class NetDioSimpleDemoPage extends StatefulWidget {
@override
_NetDioSimpleDemoPageState createState() => _NetDioSimpleDemoPageState();
}
class _NetDioSimpleDemoPageState extends State<NetDioSimpleDemoPage> {
var _items = []; //热卖实体类
OnlyDataBean onlyDataBean; //更新热卖商品返回bean
/*
测试get请求
可以将baseUrl和接口地址换成自己的测试
*/
void _testGet() async {
DioManager.getInstance()
.get('/calendar/otherFunction/getOnlineSpecialGoods', {},
//正常回调
(data) {
setState(() {
//更新UI等
this._items.clear();
this._items.addAll(HotSaleBean.fromJson(data).data);
_showToast("获取热卖商品成功");
});
},
//错误回调
(error) {
print("网络异常,请稍后重试");
});
}
/*
* 测试post请求
可以将baseUrl和接口地址换成自己的测试
*/
void _testPost() async {
DioManager.getInstance().post(
'/calendar/otherFunction/modifySpecialGoodsByParam',
FormData.fromMap({
"id": "1",
"title": "换妆品",
"contentDesc": "换妆品",
"landingPage": "https://s.click.taobao.com/YlCLjtu"
}),
//正常回调
(data) {
setState(() {
//更新UI等
setState(() {
onlyDataBean = OnlyDataBean.fromJson(data);
_showToast("修改热卖商品成功,重新获取查看");
});
});
},
//错误回调
(error) {
print("网络异常,请稍后重试");
});
}
/*
* toast提示
*/
_showToast(String s) {
Fluttertoast.showToast(
msg: s,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.grey,
fontSize: 16,
toastLength: Toast.LENGTH_SHORT,
textColor: Colors.white);
}
/*
* 热卖商品列表
*/
Widget _getListData(context, index) {
return ListTile(
title: Text(this._items[index].title),
subtitle: Text(this._items[index].contentDesc),
);
}
@override
void initState() {
super.initState();
// _testGet();
// _testPost();
}
@override
Widget build(BuildContext context) {
return getBaseThemeBar(
'测试使用dio网路库',
Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
RaisedButton(
child: Text('修改热卖商品'),
onPressed: () {
setState(() {
_testPost();
});
}),
RaisedButton(
child: Text('获取热卖商品'),
onPressed: () {
setState(() {
_testGet();
});
}),
Expanded(
child: ListView.builder(
itemBuilder: _getListData, itemCount: this._items.length))
],
),
));
}
}
demo中使用的三方库
#flutter中的提示
fluttertoast: ^7.1.5
#网络库-dio
dio: 3.0.10
#网络库-cookie
cookie_jar: ^1.0.0
#网络库-cookieManager
dio_cookie_manager: 1.0.0