【问题标题】:Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'未处理的异常:类型“_InternalLinkedHashMap<String, dynamic>”不是“Iterable<dynamic>”类型的子类型
【发布时间】:2020-07-14 11:36:36
【问题描述】:

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

`{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"
    });
  }
}

当我导航到此页面时,出现以下异常:

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>

我是 API 新手,所以我不知道如何解决这个问题。任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    json.decode(response.body) 返回一个 Map 类型的对象,它在 dart 内部表示为 _InternalLinkedHashMap&lt;String, dynamic&gt;。您可以通过指向您提供的 API 的链接查看此地图的结构。您想要的数据在字段data 下的此 Map 类型对象内,然后是 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 类 (https://api.flutter.dev/flutter/dart-core/Iterable/map.html) 的 .map 的方法签名。

    【讨论】:

    • 我试过了,我不得不将国家的类型更改为 List 并且异常消失了。但是,当我将国家/地区打印到控制台时,它会返回一个带有“CovidData”实例的列表字段
    • 是的,这就是您的代码所做的。您使用CovidData.fromJsonresponse['data']['covid19Stats'] 的每个元素转换为CovidData 对象
    • 但是如何获取 CovidData 中的元素?
    • 您可以访问属性。 countries[0]CovidData 的一个实例。 countries[0].city 会给你城市,countries[0].country 会给你国家等等。
    猜你喜欢
    • 2021-09-20
    • 2021-08-01
    • 2021-07-21
    • 2021-09-12
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多