_TypeError(类型'_InternalLinkedHashMap <String,dynamic>'不是类型'Iterable <dynamic>'的子类型)

时间:2020-08-05 09:40:23

标签: json laravel api flutter flutter-web

从api获取单个用户时,我遇到了标题中提到的错误,我的答复是

{"success":true,"data":{"id":4,"user_id":"4","email":"xyz@example.com","secondaryPhone":"+2515465465465"},"message":"User retrieved successfully."}

我的模特班

class UsersModel({this.id, this.user_id, this.email, this.secondaryPhone});

我的api调用如下

class UsersApi {
  Future<List<UsersModel>> fetchUsersById(String uId) async 
 {String singleUser = CallApi.url+CallApi.sinleUser+uId; 
   
 Map<String,String> headers =  
  { 'Accept' : 'application/json'};  
  var response = await http.get(singleUser ,headers:headers);  
       List<UsersModel> users= List<UsersModel>();
    if(response.statusCode == 200){
      var jsonData = jsonDecode(response.body);
      var data = jsonData["data"];
      for( var userr in data ) // error comes on this line
{        
UsersModel user = UsersModel(
id:item["id"].toString(),
user_id:item["user_id"].toString(),
email:item["email"].toString(),
secondaryPhone:item["secondaryPhone"].toString(),
);
 users.add(user);
      }
}
  return users;
}


}

任何帮助。

1 个答案:

答案 0 :(得分:0)

您显示的JSON不包含任何列表。您暗示,当您获取多个用户时,此代码可以正常工作,可能是因为jsonData["data"]实际上在您获取多个用户时返回了List

要解决此问题,您应该检查jsonData["data"]的类型。如果它是List,请执行当前操作,否则,将以不同的方式处理它。

例如。

Future<List<UsersModel>> fetchUsersById(String uId) async {
  String singleUser = CallApi.url+CallApi.sinleUser+uId;
   
 Map<String,String> headers =  
  { 'Accept' : 'application/json'};  
  var response = await http.get(singleUser ,headers:headers);  
       List<UsersModel> users= List<UsersModel>();
    if(response.statusCode == 200){
      var jsonData = jsonDecode(response.body);
      var data = jsonData["data"];

      //Handle data differently if it's a Map
      if(data is Map) {
        UsersModel user = UsersModel(
          id:item["id"].toString(),
          user_id:item["user_id"].toString(),
          email:item["email"].toString(),
          secondaryPhone:item["secondaryPhone"].toString(),
        );
        users.add(user);
        return users;
      }

      //Otherwise, do what you currently have
      for( var userr in data )
      {        
        UsersModel user = UsersModel(
          id:item["id"].toString(),
          user_id:item["user_id"].toString(),
          email:item["email"].toString(),
          secondaryPhone:item["secondaryPhone"].toString(),
        );
        users.add(user);
      }
  }
  return users;
}