【发布时间】:2021-07-11 20:48:36
【问题描述】:
在这里,我正在尝试创建一个未来的列表视图构建器,收到一条错误消息:_TypeError (type 'List' is not a subtype of type 'Map') 颤动。我需要在列表视图中获取帖子中的所有数据。使用 JSON 到 dart 转换器 quicktype.io 创建模型类
未来的召唤
Future<Posts> getPosts() async {
try {
final response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));
var data = jsonDecode(response.body);
return Posts.fromJson(data);
} catch (e) {
print(e);
}
}
型号
List<Posts> postsFromJson(String str) => List<Posts>.from(json.decode(str).map((x) => Posts.fromJson(x)));
String postsToJson(List<Posts> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Posts {
Posts({
this.userId,
this.id,
this.title,
this.body,
});
int userId;
int id;
String title;
String body;
factory Posts.fromJson(Map<String, dynamic> json) => Posts(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}
【问题讨论】:
标签: flutter dart flutter-web