九、Dio⽹络请求与JSON数据解析
⼀、Dio的使⽤⼊门
Dio是⼀个强⼤的Dart Http请求库,⽀持,全局配置,FormData,请求取消,⽂件下载,超时等。
添加依赖
在pubspec.yaml中添加依赖。
dependencies:
dio:2.1.7
import'package:dio/dio.dart';
class DioUtil {
Dio _dio;
static final DioUtil _instance = DioUtil._internal();
factory DioUtil()=> _instance;
DioUtil._internal(){
init();
}
/// 初始化请求配置
init(){
BaseOptions baseOptions =BaseOptions(
baseUrl:"",
connectTimeout:15000,
);
_dio =Dio(baseOptions);
}
/// 请求(默认get)
Future requset(String url,{String method ="get", Map<String, dynamic> params}) async {
Options options =Options(method: method);
try{
final result =
await _quest(url, queryParameters: params, options: options);
return result;
} on DioError catch(error){
throw error;
}
}
}
使⽤:
DioUtil()
.requset("/getxxx", params:{"page": page,"count":"20"})
.then((result){
print(result);
}).catchError((error){
print(error);
});
⼆、JSON数据解析
有多种⽅式。
2.1使⽤json.decode()⽅法
引⼊dart:convert库
json.decode() ⽅法会将 String类型数据解析成Map数据结构:Map<String, dynamic>, 取数据的格式为object[key]。对于不复杂的JOSN数据使⽤json.decode()⽅法是⼀个不错的选择
2.2编写实体类
// To parse this JSON data, do
//
// final wangyiModel = wangyiModelFromJson(jsonString);
import'dart:convert';
WangyiModel wangyiModelFromJson(String str)=> WangyiModel.fromJson(json.decode(str)); String wangyiModelToJson(WangyiModel data)=> Json());
class WangyiModel {
WangyiModel({
});
int code;
String message;
List<Result> result;
factory WangyiModel.fromJson(Map<String, dynamic> json)=>WangyiModel(
code: json["code"],
message: json["message"],
result: List<Result>.from(json["result"].map((x)=> Result.fromJson(x))),
);
Map<String, dynamic>toJson()=>{
"code": code,
"message": message,
"result": List<dynamic>.from(result.map((x)=> x.toJson())),
};
}
class Result {
Result({
this.path,
this.image,
this.title,
this.passtime,
});
String path;
String image;
String title;
DateTime passtime;
factory Result.fromJson(Map<String, dynamic> json)=>Result(
安卓在线解析jsonpath: json["path"],
image: json["image"],
title: json["title"],
passtime: DateTime.parse(json["passtime"]),
);
Map<String, dynamic>toJson()=>{
"path": path,
"image": image,
"title": title,
"passtime": Iso8601String(),
};
}
使⽤:
List<Result> _wangyiResultList;
DioUtil()
.requset("/getxxx", params:{"page": page,"count":"20"})
.then((result){
_wangyiResultList.addAll(wangyiModelFromJson(result).result);
}).catchError((error){
print(error);
});
2.3⾃动⽣成实体类
使⽤json_serializable:
引⼊库:
dependencies:
json_annotation:^2.4.0
dev_dependencies:
build_runner:^1.0.0
json_serializable:^3.0.0
Terminal中运⾏flutter packages get命令,⽤来在项⽬中使⽤这些新的依赖项
实现实体类:
import'package:data_plugin/bmob/table/bmob_object.dart';
import'package:data_plugin/bmob/table/bmob_user.dart';
import'package:json_annotation/json_annotation.dart';
/
/ ip.g.dart 将在我们运⾏⽣成命令后⾃动⽣成
part 'wangyi_dart';
//告诉⽣成器,这个类需要⽣成Model类
@JsonSerializable()
class NewsBean extends BmobObject {
BmobUser user;
String path;
String image;
String title;
DateTime passtime;
NewsBean();
@override
Map getParams(){
// TODO: implement getParams
return toJson();
}
//此处与类名⼀致,由指令⾃动⽣成代码
factory NewsBean.fromJson(Map<String, dynamic> json)=>
_$NewsBeanFromJson(json);
//此处与类名⼀致,由指令⾃动⽣成代码
Map<String, dynamic>toJson()=> _$NewsBeanToJson(this);
}
关键的在于@JsonSerializable(),它⽤于告诉⽣成器,此类是需要⽣成的Model类。在Terminal窗⼝运⾏如下命令⽣成.g.dart⽂件。flutter packages pub run build_runner build
源代码⽣成器会在同⼀个⽬录下⽣成Ip.g.dart
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论