首页 > 解决方案 > 在列表中users = [] ------ 未处理的异常:类型 '(dynamic) => Null' 不是类型 '(String, dynamic) => void' of 'f' 的子类型

问题描述

我是劳尔,我需要一些帮助

错误

未处理的异常:类型 '(dynamic) => Null' 不是类型 '(String, dynamic) => void' of 'f' 的子类型

用户类


class User {
  final String Nome, Email, Senha;

  User({@required this.Nome, @required this.Email, @required this.Senha});

  factory User.fromJson(Map<String, dynamic> jsonuser) {
    return User(
        Email: jsonuser['Email'] as String,
        Nome: jsonuser['Nome'] as String,
        Senha: jsonuser['Senha'] as String);
  }
}

上课

Future<List<User>> findExists() async {
  String urlLogReg = "https://weblogin.conveyor.cloud/api/login";
  var response = await get(Uri.parse("$urlLogReg?email=$EmailRL"),
      headers: {'Content-Type': 'application/json'});
  if (response.statusCode == 200 && response.body != null) {
    var JsonData = json.decode(response.body);
    print(JsonData);
    List<User> users = [];
    JsonData.forEach((userData) {
      User user = User.fromJson(userData);
      users.add(user);
    }
   );
  }else{
    throw Exception('falha ao pegar dados');
  }
}

非常感谢您的帮助,祝您有美好的一天

标签: androidflutter

解决方案


好的,错误在这里:

    var JsonData = json.decode(response.body);
    JsonData.forEach((userData) {
      User user = User.fromJson(userData);
      users.add(user);
    }

因为 JsonData 是一个 Map<String,dynamic> 并且在你的匿名函数中,userData当你有两个时,你只需要一个项目,键和值,因此错误。

这是你在 forEach 中的函数 (userData) {...}

(动态)=> 空

现在对于解决方案,您可能应该使用 map 方法将 JsonData 转换为 User 对象。

...

  if (response.statusCode == 200 && response.body != null) {
    var JsonData = json.decode(response.body)as List;// Presumably you are fetching a list of Users [] so i cast the result to a List
    print(JsonData);
    List<User> users = JsonData.map((e)=>User.fromJson(e)).toList();
//Here I can map passing just one argument because I casted my JsonData to a List and List's only have a value.
// Then i call toList() as the map method returns an Iterable ,not a List.
return users;
   );
  }
...

希望这对您有所帮助 如果您的项目开始变大,我建议您使用 json_serializable 之类的包或快速访问https://app.quicktype.io。序列化是重复的并且容易出错,如果你可以自动化它,那就更好了。


推荐阅读