总体的思路,
总的来说封装了这么多就是为了后期使用方便。
1、dio_utils.dart
import 'dart:async';
import 'package:dio/dio.dart';
import 'err_code.dart';
import 'method.dart';
class DioNetUtils {
static final DioNetUtils _singleton = DioNetUtils._init();
static Dio _dio;
static const String text_type = "application/json; charset=utf-8";
static const String from_type = "application/x-www-form-urlencoded";
/// 是否是debug模式.
static bool _isDebug = true;
/// 打开debug模式.
static void openDebug() {
_isDebug = true;
}
DioNetUtils._init() {
BaseOptions options = new BaseOptions(
baseUrl: "https://www.baidu.com",
connectTimeout: 1000 * 10,
receiveTimeout: 1000 * 10,
headers: {},
//表示期望以那种格式(方式)接受响应数据。
// 接受4种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`,
responseType: ResponseType.json,
);
_dio = Dio(options);
//添加拦截器
_dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options) {
print("\n================== 请求数据 ==========================");
print("url = ${options.uri.toString()}");
print("headers = ${options.headers}");
print("params = ${options.data}");
},
onResponse: (Response response) {
print("\n================== 响应数据 ==========================");
print("code = ${response.statusCode}");
print("data = ${response.data}");
print("\n");
},
onError: (DioError e) {
print("\n================== 错误响应数据 ======================");
print("type = ${e.type}");
print("message = ${e.message}");
print("\n");
}
));
}
factory DioNetUtils() {
return _singleton;
}
/// Make http request with options.
/// [method] The request method.
/// [path] The url path.
/// [data] The request data
/// [options] The request options.
/// String 返回 json data .
Future
err_code.dart
/*
* 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;
}
method.dart
/// 请求方法.
class Method {
static const String get = "GET";
static final String post = "POST";
static final String put = "PUT";
static final String head = "HEAD";
static final String delete = "DELETE";
static final String patch = "PATCH";
}
2、service_api.dart 请求服务封装
import 'dart:async';
import 'package:dio/dio.dart';
import 'common/dio_utils.dart';
import 'common/method.dart';
class ServiceNetApi {
Future
3、请求参数Model封装
import 'package:flutter/material.dart';
class RequireModel {
String prov;
String parm;
RequireModel ({
@required this.prov, // 必须传递的参数使用@require修饰
this.parm
});
/// 实体类转 Map
Map toJson() {
final Map data = new Map();
data['prov'] = this.prov;
data['parm'] = this.parm;
return data;
}
}
返回数据
{
"code": 0,
"data": [
{
"addr": "shanghai",
"name": "java"
},
{
"addr": "beijing",
"name": "c"
}
],
"msg": "success"
}
4、list_entity.dart 封装如下
class ListEntity {
int code;
List data;
String msg;
/// Map 转实体类
ListEntity.fromJson(Map json) {
this.code = json['code'];
this.data = json['data'];
this.msg = json['msg'];
}
}
5、返回的一个people_entity.dart Model 对象封装
class PersionEntity {
String name;
String addr;
/// Map 转实体类
PersionEntity.fromJson(Map json) {
this.name= json['name'];
this.addr= json['addr'];
}
}
6、使用
void _getPeopleInfos() async {
await ServiceNetApi()
.getPersons(RequireModel(prov:'aa',parm:'bb').toJson())
.then((value) {
ListEntity entity = ListEntity.fromJson(value);
if (entity.code == 0) {
/// 解析数据
List list = entity.data
.map((e) => PersionEntity.fromJson((e as Map)))
.toList();
// do something...
setState(() {});
} else {
print('get failed');
}
}).catchError((e) {
print('get failed e = $e');
});
}