在flutter里面要实现网络的请求,dio这个框架是flutter里面用途最广的框架。官网仓库传送门
第一步:将dio: ^replace-with-latest-version
添加到pubspec.yaml
文件中,添加之后记得运行一下Pub get
,去同步拉去依赖。我的版本是5.0.0,可安装官网文档的最新版本进行配置
dependencies:
dio: ^5.0.0
第二步,在页面中使用:导人import ‘package:dio/dio.dart’;创建一个Dio(),
GET请求:
import 'package:dio/dio.dart';
final dio = Dio();
void getHttp() async {
final response = await dio.get('https://dart.cn');
print(response);
}
POST请求:
response = await dio.post('/test', data: {'id': 12, 'name': 'dio'});
多个并发请求:
response = await Future.wait([dio.post('/info'), dio.get('/token')]);
下载文件:
response = await dio.download(
'https://www.google.com/',
(await getTemporaryDirectory()).path + 'google.html',
);
以流的方式接收响应数据:
final rs = await dio.get(
url,
options: Options(responseType: ResponseType.stream), // 设置接收类型为 `stream`
);
print(rs.data.stream); // 响应流
以二进制数组的方式接收响应数据:
final rs = await Dio().get>(
url,
options: Options(responseType: ResponseType.bytes), // 设置接收类型为 `bytes`
);
print(rs.data); // 类型: List
发送 FormData:
final formData = FormData.fromMap({
'name': 'dio',
'date': DateTime.now().toIso8601String(),
});
final response = await dio.post('/info', data: formData);
通过 FormData 上传多个文件:
final formData = FormData.fromMap({
'name': 'dio',
'date': DateTime.now().toIso8601String(),
'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
'files': [
await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'),
await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'),
]
});
final response = await dio.post('/info', data: formData);
监听发送(上传)数据进度:
final response = await dio.post(
'https://www.dtworkroom.com/doris/1/2.0.0/test',
data: {'aa': 'bb' * 22},
onSendProgress: (int sent, int total) {
print('$sent $total');
},
);
以流的形式提交二进制数据:
// Binary data
final postData = [0, 1, 2];
await dio.post(
url,
data: Stream.fromIterable(postData.map((e) => [e])), // 构建 Stream>
options: Options(
headers: {
Headers.contentLengthHeader: postData.length, // 设置 content-length.
},
),
);
注意:如果要监听提交进度,则必须设置content-length,否则是可选的。