Flutter网络请求使用的是Dio。Dio是一个强大易用的dart http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载…….
Flutter json数据解析是使用了json_serializable package包。它是一个自动化源代码生成器,可以为我们生成JSON序列化模板。由于序列化代码不再由我们手写和维护,我们将运行时产生JSON序列化异常的风险降至最低。
Flutter网络请求数据并且展示效果图:
数据接口
数据是使用的聚合数据的API,影讯API合集,大家可以注册个账号,申请使用一下,像这样
添加依赖
在pubspec.yaml文件中添加所需要的第三方依赖库
environment:
sdk: " =2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
json_annotation: ^2.0.0
connectivity: ^0.4.2
dio: ^2.0.15
event_bus: ^1.0.3
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
网络请求过程分析
static netFetch(url,params,Map<String,String header,Options option,{
noTip = false}) async {
//获取网络的连接状态,如果没有连接网络,返回NETWORK_ERROR
var connectivityResult = await (new Connectivity().checkConnectivity());
if(connectivityResult == ConnectivityResult.none) {
return new ResultData(Code.errorHandleFunction(Code.NETWORK_ERROR, "", noTip),false,Code.NETWORK_ERROR);
}
//请求头存放集合
Map<String,String headers = new HashMap();
if(header != null) {
headers.addAll(header);
}
//option存放请求的一些配置信息
if(option != null) {
option.headers = headers;
}else {
//get请求
option = new Options(method:'get');
option.headers = headers;
}
//超时时间15000ms
option.connectTimeout = 15000;
//创建dio对象
Dio dio = new Dio();
Response response;
try{
//执行网络请求,await和async配合使用,表示这是一个异步耗时操作
//执行结果不会立马返回。
response = await dio.request(url,data: params,options: option);
}on DioError