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

Posted

技术标签:

【中文标题】type _InternalLinkedHashMap<String, dynamic> 不是 List<dynamic> 类型的子类型【英文标题】:type _InternalLinkedHashMap<String, dynamic> is not subtype of type List<dynamic> 【发布时间】:2019-01-26 23:43:34 【问题描述】:

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

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

type _InternalLinkedHashMap 不是 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",

根据我的理解,我只是想先在列表中显示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 结构的文章,但似乎无法弄清楚如何解决这个问题。

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

感谢@Rémi Rousselet。我现在收到The argument type string can't be assigned to parameter type int。如何将语句转换为 int ?在您建议的更改之后,它是否类似于.cast&lt;int&gt;(); int.parse(myString) 在进行以下更改后,我仍然遇到同样的错误。列出 responseJson = json.decode(response.body.toString()); List newsTitle = createNewsList(responseJson[int.parse("response")][int.parse("results")]); @Rémi Rousselet。你能帮我解决这个问题吗? @Rémi Rousselet 你能帮我解决这个问题吗? https://***.com/q/56524623/1830228 谢谢【参考方案2】:
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

【讨论】:

【参考方案3】:

Mybe你可以试试修改这个方法,像这样:

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;


【讨论】:

【参考方案4】:

你可以用这个

Map<String, String> stringParams = ;

或者

var stringParams = <String, String>;

【讨论】:

以上是关于type _InternalLinkedHashMap<String, dynamic> 不是 List<dynamic> 类型的子类型的主要内容,如果未能解决你的问题,请参考以下文章

Python type 与 __bases__

type和object

Detect types in python2

OpenCV FAST TYPE_5_8

`__metaclass__ = type` 的目的是啥?

__http原理__03__content-type 对照表