[英]How to create user model with nested map field for cloud firestore with flutter?
我想创建一个类型为 map 的嵌套字段。 'usersName'是类型为 map 的字段,包含'firstName'和'lastName' 。 这是图像: 如果你需要源代码,请告诉我。 谢谢
用户模型.dart
class User {
String id;
String name;
String email;
String password;
String phone;
User({
required this.id,
required this.name,
required this.email,
required this.password,
required this.phone,
});
//and i dont know how to make it work
}
进行此更改,您将能够根据需要接收它:
class User {
String id;
Map<String, String> name;
String email;
String password;
String phone;
User({
required this.id,
required this.name,
required this.email,
required this.password,
required this.phone,
});
//and i dont know how to make it work
}
有关 dart 地图的更多信息: https://dart.dev/guides/language/language-tour#maps
您可以使用firstName
和lastName
变量创建一个UserName
class ,然后在您的User
class 上将您的name
从String
更改为UserName
。
class User {
String id;
UserName name;
String email;
String password;
String phone;
User({
required this.id,
required this.name,
required this.email,
required this.password,
required this.phone,
});
}
class UserName {
String firstName;
String lastName;
UserName({
required this.firstName,
required this.lastName,
});
}
我同意将name
属性设置为Map
是通往 go 的方式。例如,您的用户名如下:
var name = {firstName: "Joe", lastName: "Smith"}
如上所述创建您的User
class 然后创建方法来相应地转换您的属性。 在这里,我创建了toMap()
以返回用户的 Map object。
class User {
String id;
Map<String, String> name;
String email;
String password;
String phone;
User({
required this.id,
required this.name,
required this.email,
required this.password,
required this.phone,
});
// if you intend to store this User object into a database/storage
// that requires Map object
Map<String, dynamic> toMap() {
// convert Map to String
var fullName = name.toString();
return {
'id': id,
// String key, String value
'name': fullName,
...
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.