I want to create a nested field with the type of map. 'usersName' is the field that has the type of map, contain 'firstName' and 'lastName' . Here is the image: If you need a source code, tell me. Thank you
user_model.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
}
Do this change and you will be able to receive it as you want:
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
}
More information on dart Maps: https://dart.dev/guides/language/language-tour#maps
You can create a UserName
class with firstName
and lastName
variables and then on your User
class you change your name
from String
to 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,
});
}
I agree that setting the name
property as Map
is the way to go. For example, you have your user name as follow:
var name = {firstName: "Joe", lastName: "Smith"}
Create your User
class as above then create method to convert your properties accordingly. Here I created toMap()
to return a Map object of the User.
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,
...
};
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.