在flutter中优雅的封装网络请求

本文讲述如何封装dio网络请求,并在实际中使用。

Dio http库

dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时等。

引入

引入dio:

1
2
dependencies:
dio: ^x.x.x #请使用pub上的最新版本

开始封装

在lib文件夹下创建utils/dio/dio.dart,用于编写我们封装的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// 自定义枚举
enum Method { get, post, put, delete }
class Net {
// 工厂模式
factory Net() => _getInstance();
static Net get instance => _getInstance();
static Net _instance;

Dio dio;
Net._internal() {
// 初始化
dio = Dio(BaseOptions(
connectTimeout: 60000, // 连接服务器超时时间,单位是毫秒.
receiveTimeout: 10000, // 响应流上前后两次接受到数据的间隔,单位为毫秒, 这并不是接收数据的总时限.
));
}
// 单列模式
static Net _getInstance() {
if (_instance == null) {
_instance = Net._internal();
}
return _instance;
}
get(String url, Map<String, dynamic> params) {
return _doRequest(url, params, Method.get);
}
post(String url, Map<String, dynamic> params) {
return _doRequest(url, params, Method.post);
}
put(String url, Map<String, dynamic> params) {
return _doRequest(url, params, Method.put);
}
delete(String url, Map<String, dynamic> params) {
return _doRequest(url, params, Method.delete);
}
_doRequest(
String url,
Map<String, dynamic> params,
Method method,
) async {
try {
var _prefs = await SharedPreferences.getInstance();
var token = _prefs.getString('token')??'';
/// 可以添加header 设置token
dio.options.headers.addAll({'Authorization': 'Bearer ' + token});
String BASE_URL = '你的接口地址' + url;
Response response;
switch (method) {
case Method.get:
if (params != null && params.isNotEmpty) {
response = await dio.get(BASE_URL, queryParameters: params);
} else {
response = await dio.get(BASE_URL);
}
break;
case Method.post:
if (params != null && params.isNotEmpty) {
response = await dio.post(BASE_URL, queryParameters: params);
} else {
response = await dio.post(BASE_URL);
}
break;
case Method.put:
if (params != null && params.isNotEmpty) {
response = await dio.put(BASE_URL, queryParameters: params);
} else {
response = await dio.put(BASE_URL);
}
break;
case Method.delete:
if (params != null && params.isNotEmpty) {
response = await dio.delete(BASE_URL, queryParameters: params);
} else {
response = await dio.delete(BASE_URL);
}
break;
}
return json.decode(response.toString());
} catch (exception) {
print('错误:${exception.toString()}');
}
}
}
class BaseModel {
int code;
dynamic data;
String error;
BaseModel({this.code, this.data, this.error});
BaseModel.fromJson(Map<String, dynamic> json) {
code = json['code'];
data = json['data'];
error = json['error'];
}
}

使用

我们以一个登陆的demo来看dio的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zzc_app/utils/dio/dio.dart';

class LoginForm extends StatefulWidget {
LoginForm({Key key}) : super(key: key);
@override
_LoginFormState createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final _userNameController = TextEditingController();
final _pwdController = TextEditingController();

_onsubmit() async {//进行登陆操作
var params={
'username':_userNameController.text,
'password':_pwdController.text
};
var res = await Net().post('login', params);
if(res['code']==1){
//登陆成功的操作
}else{
//登陆失败的操作
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsetsDirectional.fromSTEB(30, 100, 30, 10),
child: Column(
children: <Widget>[
TextField(
controller: _userNameController,
decoration: InputDecoration(
labelText: '用户名',
),
),
TextField(
controller: _pwdController,
decoration: InputDecoration(
labelText: '密码',
),
),
MaterialButton(onPressed: _onsubmit,//等同于我们常见的click事件
child: Text('登陆'))
],
),
));
}
}

将uni-request进行axios化封装
在vue中对axios进行二次封装

文章作者: Joker
文章链接: https://qytayh.github.io/2020/08/%E5%9C%A8flutter%E4%B8%AD%E4%BC%98%E9%9B%85%E7%9A%84%E5%B0%81%E8%A3%85%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Joker's Blog