Flutter JSON Array Parsing getting error : Exception: type '(dynamic) => xxx is not a subtype of type '(Map<String, dynamic>) => List<xxx>' of 'f'

Flutter JSON Array Parsing getting error : Exception: type '(dynamic) => xxx is not a subtype of type '(Map<String, dynamic>) => List<xxx>' of 'f'

抱歉,如果它重复了这个问题,但我没有找到解决方案。

错误:

Exception: type '(dynamic) => PostalModel' is not a subtype of type '(Map<String, dynamic>) => List' of 'f'

我做了什么:

  1. 正在调用 API:

    Future<PostalModel> fetchPhotos(http.Client client) async {
       final response =
        await client.get('https://api.postalpincode.in/pincode/364710');
    
       // Use the compute function to run parsePhotos in a separate isolate.
       return compute(parsePostalPincode, response.body);
    }
    
  2. 正在解析JSON:

     // A function that converts a response body into a List.
     PostalModel parsePostalPincode(String responseBody) {
       print(responseBody);
       final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
       print('Parsed : $parsed'); //Getting Log OUTPUT
       PostalModel postalModel = parsed.map<List<PostalModel>>((json) => PostalModel.fromJson(json));
       print('Postal Model : $postalModel'); //Getting Log OUTPUT
       return postalModel;
     }
    
  3. 正文中的绑定数据:

    body: FutureBuilder<PostalModel>(
      future: fetchPhotos(http.Client()),
      builder: (context, snapshot) {
        print('snapshot $snapshot'); // Getting Error Here
        // "AsyncSnapshot<PostalModel>(ConnectionState.done, null, Exception: type '(dynamic) => PostalModel' is not a subtype of type '(Map<String, dynamic>) => List<PostalModel>' of 'f')"
        if (snapshot.hasError) print(snapshot.error);
    
        return snapshot.hasData
           ? PostOfficeList(postOfficeList: snapshot.data.postOffice)
           : Center(child: CircularProgressIndicator());
      },
    ),
    

您可以从 API Link 检查 JSON 我已经从 here.

创建了一个模型 class

API returns JSON 数组,而不是 JSON 对象,所以是 List,而不是 Map。

即如果您的模型 class 名称是 User,则 User JSON 是 JSON 数组的第一个元素。

因此要获取第一个元素,请使用第一个索引。内部获取信息更新

return Users.fromJson(jsonresponse[0]);

最后,我通过以下解决方案获得了成功:

// A function that converts a response body into a List.
PostalModel parsePostalPincode(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  print('Parsed : $parsed[0]'); 
  PostalModel postalModel = PostalModel.fromJson(parsed[0]);
  print('Postal Model : $postalModel');
  return postalModel;
}

Flutter 对新手来说太疯狂了。 :P