type _InternalLinkedHashMap<String, dynamic> 不是 List<dynamic> 类型的子类型

Dar*_*han 5 json flutter

我正在尝试使用网络调用实现一个简单的新闻提要应用程序,其中屏幕将在 Listview 中显示最新故事。

使用当前代码,我从 API 得到响应(因为我在日志中看到了整个响应主体),但似乎无法在 UI 中显示数据。我收到此错误:

type _InternalLinkedHashMap<String, dynamic> 不是 List 类型的子类型

这是 JSON 结构

{
    "response": {
        "status": "ok",
        "userTier": "developer",
        "total": 25095,
        "startIndex": 1,
        "pageSize": 10,
        "currentPage": 1,
        "pages": 2510,
        "orderBy": "relevance",
        "results": [
          {
            "id": "australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
            "type": "article",
            "sectionId": "australia-news",
            "sectionName": "Australia news",
            "webPublicationDate": "2018-08-12T18:00:08Z",
            "webTitle": "Energy policy hangs in balance, as Senate debates euthanasia",
            "webUrl": "https://www.theguardian.com/australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
            "apiUrl": "https://content.guardianapis.com/australia-news/2018/aug/13/turnbulls-energy-policy-hangs-in-the-balance-as-euthanasia-debate-given-precedence",
            "isHosted": false,
            "pillarId": "pillar/news",
            "pillarName": "News"
        }, {
            "id": "media/2018/jun/13/the-rev-colin-morris-obituary-letter",
            "type": "article",
            "sectionId": "media",
Run Code Online (Sandbox Code Playgroud)

对于我的理解,我只是想先webTitle在列表中显示,然后再添加其他字段(在我清楚地了解网络概念之后),但得到了上面提到的错误。这是我的完整代码:

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return new MaterialApp(
      title: 'Network Example',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: AppBar(
          title: new Text('Network Example'),
        ),
        body: new Container(
          child: new FutureBuilder<List<News>> (
            future: fetchNews(),
            builder: (context, snapshot) {

              if (snapshot.hasData) {
                return new ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Text(snapshot.data[index].newsTitle,
                                style: new TextStyle(
                                    fontWeight: FontWeight.bold)
                            ),
                            new Divider()
                          ],
                      );
                    }
                );
              } else if (snapshot.hasError) {
                return new Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }


Future<List<News>> fetchNews() async {
  final response = await http.get('https://content.guardianapis.com/search?q=debates&api-key=');
  print(response.body);
  List responseJson = json.decode(response.body.toString());
  List<News> newsTitle = createNewsList(responseJson);
  return newsTitle;

}

List<News> createNewsList(List data) {
    List<News> list = new List();
    for (int i = 0; i< data.length; i++) {
      String title = data[i]['webTitle'];

      News news = new News(
      newsTitle: title);
      list.add(news);
    }
    return list;

  }
}

class News {
 final String newsTitle;

  News({this.newsTitle});

  factory News.fromJson(Map<String, dynamic> json) {

    return new News(
      newsTitle: json['webTitle'],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我之前看过类似的问题,也看过 json 结构文章,但似乎无法弄清楚如何解决这个问题。

Rém*_*let 5

问题是,你的 JSON 不是数组。它是一个物体。但你试图将它用作数组。

您可能需要将createNewsList呼叫更改为以下内容:

List responseJson = json.decode(response.body.toString());
List<News> newsTitle = createNewsList(responseJson["response"]["results"]);
Run Code Online (Sandbox Code Playgroud)