簡體   English   中英

Flutter 錯誤:[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未處理的異常:輸入“列表”<dynamic> &#39; 不是類型 &#39;Map 的子類型<String, dynamic> &#39;

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

我想從 api 獲取列表視圖並將其放入我的應用程序屏幕,但它向我顯示

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

在我的提供者中,我添加了我需要的未來,但現在有錯誤,我無法運行登錄應用程序

List<Country> _country;
List<Country> get country => _country;

Future<dynamic> countryList() async {
    _isLoading = true;
    notifyListeners();

      http.Response  response = await http.get(Environment.country,
        headers: Environment.requestHeader);

    Map<String,dynamic> res = json.decode(response.body);
    var results;
    if (res['code'] == 200) {
      _country = [];
      res['message'].forEach((v) {
        _country.add(new Country.fromJson(v));
      });
      results = true;
    } else {
      results =
          FailedRequest(code: 400, message: res['message'], status: false);
    }
    _isLoading = false;
    notifyListeners();
    return results;
  }

這是我用來返回列表的類國家的模型

class Country{
  String name;
  String photo;

  Country({
    this.name,
    this.photo,
  });

  Country.fromJson(Map<String, dynamic> json){
    name = json['countryName'];
    photo = json['countryImage'].toString();
  }
}

我的 json 響應

respond data : [{"countryName":"Egypt","countryImage":"https://i.ytimg.com/vi/TWaReNkjTLk/maxresdefault.jpg"},{"countryName":"Canada","countryImage":"https://pix10.agoda.net/geo/country/100/3_100_canada_02.jpg?s=1920x"},{"countryName":"US","countryImage":"https://www.green-card.com/assets/Uploads/living-usa-states-florida-green-card.jpg"}]

我試圖添加到列表語句,但它也不起作用!

我想問題出在這里:

Map<String,dynamic> res = json.decode(response.body);

您的 json 返回了地圖列表:

respond data : [{"countryName":"Egypt","countryImage":"https://i.ytimg.com/vi/TWaReNkjTLk/maxresdefault.jpg"},{"countryName":"Canada","countryImage":"https://pix10.agoda.net/geo/country/100/3_100_canada_02.jpg?s=1920x"},{"countryName":"US","countryImage":"https://www.green-card.com/assets/Uploads/living-usa-states-florida-green-card.jpg"}]

但是,您正在將作為列表的響應分配給地圖。

嘗試更改Map<String,dynamic> res = json.decode(response.body); List res = json.decode(response.body);

我希望它有幫助!

您的響應數據返回地圖列表!

如果您確定只有一張地圖(國家或其他任何地方),那么請更改您的

Map<String,dynamic> res = json.decode(response.body);

Map<String,dynamic> res = json.decode(response.body)[0];

如果有地圖數量(國家或其他任何地方),則更改您的

Map<String,dynamic> res = json.decode(response.body);

List<Map<String,dynamic>> res = json.decode(response.body);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM