在Flutter中从JSON创建列表 [英] Creating a list from JSON in Flutter
问题描述
下面的在线示例中,我有以下代码:
Following an online example I have the following code:
_fetchData() async {
setState(() {
isLoading = true;
});
final response = await http.get(
"https://apiurl...");
if (response.statusCode == 200) {
print(json.decode(response.body).runtimeType); // _InternalLinkedHashMap<String, dynamic>
list = (json.decode(response.body) as List)
.map((data) => Model.fromJson(data))
.toList();
setState(() {
isLoading = false;
});
} else {
throw Exception('Failed to load');
}
}
哪个会返回此错误:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
这是API的响应:
{"results":[{"docid":"123434","title":"A title"}, ...]}
型号:
class Model {
final String title;
final String docid;
Model._({this.title, this.docid});
factory Model.fromJson(Map<String, dynamic> json) {
return new Model._(
title: json['title'],
docid: json['docid'],
);
}
}
我了解以上工厂期望的论点是是 Map< String,dynamic>
,并且json的格式是不同的,可以更改,但是想知道如何使它与这种格式一起使用。
I understand that the above factory is expecting the argument to be Map<String, dynamic>
and the format of the json is different and can be changed, but want to know how to make it work with this format.
***编辑
工作列表视图
body: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: TextField(
onChanged: (value) {
...
},
controller: _searchController,
decoration: InputDecoration(
...
),
),
),
Expanded(
child: SizedBox(
height: 200.0,
child: ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Text(list[index].title);
}),
),
)
],
),
推荐答案
print(json.decode(response.body).runtimeType)
打印 _InternalLinkedHashMa的原因p
是因为json的顶层确实是一个地图; {结果:[
用大括号打开。
The reason that print(json.decode(response.body).runtimeType)
prints _InternalLinkedHashMap
is because the top level of your json is indeed a map; {"results":[
opens with a brace.
因此, json.decode (response.body)
不是列表,不能转换为一个。另一方面, json.decode(response.body)['结果']
是一个列表。
So, json.decode(response.body)
isn't a list and cannot be cast to one. On the other hand, json.decode(response.body)['results']
is a list.
您需要:
list = json.decode(response.body)['results']
.map((data) => Model.fromJson(data))
.toList();
这篇关于在Flutter中从JSON创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!