知識點來自于下方鏈接,本文只是記錄下編碼時遇到的一些問題
(2條消息) Flutter基礎(chǔ)(十一)網(wǎng)絡(luò)請求(Dio)與JSON數(shù)據(jù)解析_BATcoder - 劉望舒-CSDN博客
總結(jié):
網(wǎng)絡(luò)請求使用dio,引用時需要在pubspec.yaml中dependencies節(jié)點下配置dio: ^4.0.0。
json解析使用自帶jsonDecode,json模板代碼使用 quicktype 生成,這個網(wǎng)站非常好用。
在使用測試json地址(https://jsonplaceholder.typicode.com/posts)進(jìn)行測試的時候,發(fā)現(xiàn)如果什么都不設(shè)置,請求后返回的response直接toString進(jìn)行解析會出錯,原因是dio默認(rèn)的responseType為json,返回的response會吃掉引號導(dǎo)致解析報錯,手動設(shè)置responseType為plain即可正常解析。
具體的代碼如下:
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class RequestTest extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyState();
}
}
class MyState extends State {
@override
void initState() {
super.initState();
// loadData();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new ElevatedButton(
onPressed: loadData,
style: new ButtonStyle(),
child: new Text("start request!"))),
);
}
loadData() async {
String dataURL = "https://jsonplaceholder.typicode.com/posts";
try {
Response response =
await Dio(BaseOptions(responseType: ResponseType.plain)).get(dataURL);
print(
"request complete ! code = ${response.statusCode} message = ${response.statusMessage}");
if (response.statusCode == 200) {
List<User> users = userFromJson(response.data.toString());
var firstUser = users[66];
print(
"parse success ---- userId = ${firstUser.userId} ,title = ${firstUser.title}");
}
} catch (e) {
print('error happened ${e.toString()}');
}
}
}
List<User> userFromJson(String str) =>
List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.userId,
this.id,
this.title,
this.body,
});
int userId;
int id;
String title;
String body;
factory User.fromJson(Map<String, dynamic> json) => User(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}