Flutter 未处理的异常:类型'_内部链接dhashmap<;字符串,动态>';不是类型为';Iterable<;动态>';

Flutter 未处理的异常:类型'_内部链接dhashmap<;字符串,动态>';不是类型为';Iterable<;动态>';,flutter,Flutter,我正在尝试从API获取数据。端点中的示例数据如下所示: `{4 items "error":false "statusCode":200 "message":"OK" "data":{2 items "lastChecked":"2020-04-02T11:49:38.233Z" "covid19Stats":[15 items 0:{8 items "city":"" "province":"Alberta" "country":"Canada" "lastUpdate":"2020-04-0

我正在尝试从API获取数据。端点中的示例数据如下所示:

`{4 items
"error":false
"statusCode":200
"message":"OK"
"data":{2 items
"lastChecked":"2020-04-02T11:49:38.233Z"
"covid19Stats":[15 items
0:{8 items
"city":""
"province":"Alberta"
"country":"Canada"
"lastUpdate":"2020-04-01 22:04:44"
"keyId":"Alberta, Canada"
"confirmed":754
"deaths":9
"recovered":0
}
1:{...}8 items
2:{...}8 items
3:{...}8 items
4:{...}8 items
5:{...}8 items
6:{...}8 items
7:{...}8 items
8:{...}8 items
9:{...}8 items
10:{...}8 items
11:{...}8 items
12:{...}8 items
13:{...}8 items
14:{...}8 items
]
}
}`
我正在尝试将此数据映射到以下代码中的
CovidData
类:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class StatusPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return StatusPageState();
  }
}

class StatusPageState extends State<StatusPage>{
  @override
  void initState() {
    super.initState();
    fetch();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text(
            "COVID-19 Stats",
            style: TextStyle(
                color: Colors.white,
                fontFamily: 'Montserrat',
                fontWeight: FontWeight.bold),
          ),
        ),
      ),
      body: Container(
        child: FlatButton(onPressed: () => show(), child: Text("Fetch")),
      ),
  );
  } 

fetch(){
  API.getStats().then(
    (response) => {
      lists = json.decode(response.body),
      countries = lists.map((model) => CovidData.fromJson(model)).toList(), 
      // print(json.decode(response.body)['data']['covid19Stats'][0])
    }
  );
  setState(() {

  });
}
}

class CovidData{
  String city = "";
  String province = "";
  String country = "";
  String lastUpdate = "";
  String keyId = "";
  int confirmed = 0;
  int deaths = 0;
  int recovered = 0;

  CovidData(String city, String province, String country, String lastUpdate, String keyId, int confirmed, int deaths, int recovered){
    this.city = city;
    this.province = province;
    this.country = country;
    this.lastUpdate = lastUpdate;
    this.keyId = keyId;
    this.confirmed = confirmed;
    this.deaths = deaths;
    this.recovered = recovered;
  }

  CovidData.fromJson(Map json)
  : city = json['city'],
    province = json['province'],
    country = json['country'],
    lastUpdate = json['lastUpdate'],
    keyId = json['keyId'],
    confirmed = json['confirmed'],
    deaths = json['deaths'],
    recovered = json['recovered'];

  Iterable toJson(){
    return [
      {'city': city},
      {'province': province},
      {'country': country},
      {'lastUpdate': lastUpdate},
      {'keyId': keyId},
      {'confirmed': confirmed},
      {'deaths': deaths},
      {'recovered': recovered},
    ];
  }
}

List<CovidData> countries = [];
Iterable lists;

show(){
  print(countries);
}


const baseUrl = "https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats";

class API {
  static Future getStats(){
    return http.get(baseUrl, headers: {
      "x-rapidapi-host": "covid-19-coronavirus-statistics.p.rapidapi.com",
      "x-rapidapi-key": "8ca140a965mshe408a2e58737ba5p14b104jsn19a57561ec85"
    });
  }
}
导入'dart:convert';
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
类StatusPage扩展StatefulWidget{
@凌驾
状态createState(){
返回StatusPageState();
}
}
类StatusPageState扩展状态{
@凌驾
void initState(){
super.initState();
fetch();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:中心(
子:文本(
“新冠病毒-19统计数据”,
样式:TextStyle(
颜色:颜色,白色,
fontFamily:“蒙特塞拉特”,
fontWeight:fontWeight.bold),
),
),
),
主体:容器(
子:扁平按钮(按下时:()=>show(),子:文本(“提取”),
),
);
} 
fetch(){
API.getStats()。然后(
(回应)=>{
lists=json.decode(response.body),
countries=lists.map((model)=>CovidData.fromJson(model)).toList(),
//打印(json.decode(response.body)['data']['covid19Stats'][0])
}
);
设置状态(){
});
}
}
类CovidData{
字符串城市=”;
字符串“=”;
字符串country=“”;
字符串lastUpdate=“”;
字符串keyId=“”;
int=0;
int死亡=0;
int=0;
CovidData(字符串城市、字符串省、字符串国家、字符串最新更新、字符串密钥ID、整数确认、整数死亡、整数恢复){
this.city=城市;
这个省=省;
这个国家=国家;
this.lastUpdate=lastUpdate;
this.keyId=keyId;
这个.已确认的=已确认的;
死亡=死亡;
这个.恢复了=恢复了;
}
CovidData.fromJson(映射json)
:city=json['city'],
省=json['province'],
country=json['country'],
lastUpdate=json['lastUpdate'],
keyId=json['keyId'],
确认=json['confirm'],
Deathers=json['Deathers'],
recovered=json['recovered'];
Iterable toJson(){
返回[
{'city':city},
{'province':省},
{'country':country},
{'lastUpdate':lastUpdate},
{'keyId':keyId},
{'confirmed':confirmed},
{‘死亡’:死亡},
{'recovered':recovered},
];
}
}
列出国家=[];
可编辑列表;
show(){
印刷品(国家);
}
常量baseUrl=”https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats";
类API{
静态未来getStats(){
返回http.get(baseUrl,标题:{
“x-rapidapi-host”:“新冠病毒-19-coronavirus-statistics.p.rapidapi.com”,
“x-rapidapi-key”:“8ca140a965mshe408a2e58737ba5p14b104jsn19a57561ec85”
});
}
}
当我导航到此页面时,会出现以下异常:

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>
[错误:flatter/lib/ui/ui\u dart\u state.cc(157)]未处理的异常:类型“\u InternalLinkedHashMap”不是类型“Iterable”的子类型
我是API新手,所以我不知道如何解决这个问题。任何帮助都将不胜感激。谢谢。

json.decode(response.body)
返回一个映射类型的对象,该对象在dart中内部表示为
\u InternalLinkedHashMap
。您可以从提供的API链接中看到此映射的结构。所需的数据位于该映射类型对象内的字段
data
then
covid19Stats

  API.getStats().then(
    (response) => {
      var response = json.decode(response.body),
      countries = response['data']['covid19Stats'].map((model) => CovidData.fromJson(model)).toList(), 
      // print(json.decode(response.body)['data']['covid19Stats'][0])
    }
  );

您遇到的错误是由于调用了
.map
的方法签名,该签名属于地图类型对象上的
Iterable
类(),该对象不是Iterable。

我尝试了这个方法,并且我必须将国家类型更改为List,异常消失了。但当我将国家打印到控制台时,它会返回一个列表字段,其中包含“CovidData”是的实例,这就是您的代码所做的。您使用
CovidData.fromJson
response['data']['covid19Stats']
的每个元素转换为
CovidData
对象,但是如何获取CovidData中的元素?您可以访问属性
countries[0]
CovidData
的一个实例<代码>国家[0]。城市将为您提供城市,
国家[0]。国家将为您提供国家,依此类推。