类型_InternalLinkedHashMap <string,dynamic =“”>不是类型List <dynamic>的子类型

时间:2018-08-20 19:48:12

标签: flutter

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

使用当前代码,我正在从api获取响应(如我在日志中看到的整个响应正文),但似乎无法在UI中显示数据。我收到此错误:

  

类型_InternalLinkedHashMap不是列表类型的子类型

这是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",

据我了解,我只想首先在列表中显示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'],
    );
  }
}

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

4 个答案:

答案 0 :(得分:2)

问题是,您的json不是数组。它是一个对象。但是您尝试将其用作数组。

您可能希望将createNewsList的调用更改为以下内容:

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

答案 1 :(得分:0)

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:cricket/cric.dart';

void main() async{
  List st=await getmatches();
  runApp(cric(st));
}

class cric extends StatelessWidget{

  List st;
  cric(this.st);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.deepPurpleAccent
      ),
      home: cricket(st),
    );
  }
}

Future<List> getmatches() async{
 /* String url="https://cricapi.com/api/cricketScore?apikey=oJmzPtpZJXcIQmxAjOlP5Zss1At1&unique_id=1034809";
  http.Response response=await http.get(url);
  return jsonDecode(response.body);*/
 // print(Utf8Codec().decode((response.bodyBytes)));
  //return Utf8Codec().decode(response.bodyBytes);
 //print (utf8.decode(response.bodyBytes));
  var response= await http.get(Uri.encodeFull('https://cricapi.com/api/matches?apikey=oJmzPtpZJXcIQmxAjOlP5Zss1At1'),
  headers:{
    "Accept": "application/json",
    "X-Api-Key": "oJmzPtpZJXcIQmxAjOlP5Zss1At1",
  });
  //return json.decode(response.body);
  print(Utf8Codec().decode((response.bodyBytes)));

}//iam also having the same error

答案 2 :(得分:0)

也许您可以尝试修改此方法,如下所示:

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.result);
  List<News> newsTitle = createNewsList(responseJson);
  return newsTitle;

}

答案 3 :(得分:0)

你可以使用这个

Map<String, String> stringParams = {};

var stringParams = <String, String>{};