android - 在列表中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');
}
}
非常感谢您的帮助,祝您有美好的一天
解决方案
好的,错误在这里:
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。序列化是重复的并且容易出错,如果你可以自动化它,那就更好了。
推荐阅读
- php - codeigniter 显示 stream_socket_client(): Failed to enable crypto 这个错误在 sendmail 上?
- docker - KVM 模块未加载到容器中
- java - 在带有 Itextpdf 的 Times-New-Roman 字体中使用度数符号
- xml - 从变量加载 XML 和 XSL 并在浏览器中转换
- c++ - 使用 select() 管理多个套接字
- logstash - Logstash 多行编解码器无法识别该模式
- algorithm - 从顶点对创建图形,同时它们之间的距离最小
- android - 后退按钮正在关闭应用程序而不是返回父 Activity
- if-statement - IF 语句 - 错误 1004 [Vlookup 文件返回零]
- selenium-webdriver - 硒基本示例总是失败