在Flutter中从JSON创建列表

时间:2019-05-08 23:09:01

标签: dart flutter

下面有一个在线示例,我有以下代码:

_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的格式不同并且可以更改,但是想知道如何使其适用于这种格式。

***编辑

工作列表视图

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);
              }),
        ),
      )
    ],
  ),

4 个答案:

答案 0 :(得分:4)

print(json.decode(response.body).runtimeType)打印_InternalLinkedHashMap的原因是,您的json的顶层确实是地图。 {"results":[以大括号打开。

因此,json.decode(response.body)不是列表,不能转换为一个。另一方面,json.decode(response.body)['results'] 一个列表。

您需要:

  list = json.decode(response.body)['results']
      .map((data) => Model.fromJson(data))
      .toList();

答案 1 :(得分:3)

我尝试过这样的方法,并且有效

List<UserModel> users = (json.decode(response.body) as List)
      .map((data) => UserModel.fromJson(data))
      .toList();

我的Json响应就像:-

[{"id":4,"name":"1","email":"admin","password":"dc4b79a9200aa4630fee652bb5d7f232c503b77fb3b66df99b21ec3ff105f623","user_type":"1","created_on":"2020-01-13 12:50:28","updated_on":"2020-01-14 11:42:05","flags":"00000"},{"id":31,"name":"avi","email":"asdf@gmail.com","password":"dc4b79a9200aa4630fee652bb5d7f232c503b77fb3b66df99b21ec3ff105f623","user_type":"1","created_on":"2020-03-15 11:39:16","updated_on":"2020-03-15 11:39:16","flags":null}]

答案 2 :(得分:1)

以下内容对我有用:

List<Model>.from(
  json.decode(response.body)
  .map((data) => Model.fromJson(data))
)

答案 3 :(得分:-3)

以下解决此代码并正常工作:

最终响应=等待http.get(“ https://about.google/static/data/locations.json”);

最终数据= jsonDecode(response.body)['offices'];