[英]Firebase snapshot to json flutter model
Hello i am trying to get data from a firebase database and save it in a model class exactly the same way as you do for http json so this is my class model您好,我正在尝试从 firebase 数据库中获取数据并将其保存在模型类中,与您对 http json 所做的完全相同,所以这是我的类模型
UsersModel usersModelFromJson(String str) => UsersModel.fromJson(json.decode(str));
class UsersModel {
String age;
String heigth;
String userid;
String username;
String weigth;
UsersModel({
this.age,
this.heigth,
this.userid,
this.username,
this.weigth,
});
factory UsersModel.fromJson(Map<dynamic, dynamic> json) => UsersModel(
age: json["age"],
heigth: json["heigth"],
userid: json["userid"],
username: json["username"],
weigth: json["weigth"],
);
and this is how i try to get the data这就是我尝试获取数据的方式
Future obtenerDatos(userid) async {
var bd = dB.child('users').child(userid).once().then((DataSnapshot snapshot) {
Map<String, dynamic> values = snapshot.value;
values.forEach((key, values) {
return UsersModel.fromJson(values);
});
}
i get this error我收到这个错误
`Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'`
i have tried everything i can prit it as json but i dont understand why i cant save it to the model class i have 2 days with the same problem please help me我已经尝试了所有可以将其打印为 json 的方法,但我不明白为什么我无法将其保存到模型类中,我有 2 天遇到同样的问题,请帮助我
You have to change this line in obtenerDatos : Map<String, dynamic> values = snapshot.value;
您必须在 obtenerDatos 中更改这一行:
Map<String, dynamic> values = snapshot.value;
To: Map<dynamic, dynamic> values = snapshot.value;
至:
Map<dynamic, dynamic> values = snapshot.value;
The error happens because your fromjson method expects map of the type <dynamic, dynamic>
and you mapped the response like <String, dynamic>
发生错误是因为您的 fromjson 方法需要
<dynamic, dynamic>
类型的映射,而您映射了像<String, dynamic>
这样的响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.