In Dart, is it possible to create an object by parsing a map to constructor?
Example:
class User {
final String? id;
final String? name;
User({this.id, this.name});
}
// Using a map to initiate a `User` object, how to achieve similar functionality?
final map = {'id': '1323', 'name': 'foo'};
User foo = User(map);
CodePudding user response:
By creating a factory:
factory MyUser.fromMap(Map<String, dynamic>? map) {
if(map == null){
return MyUser( id: "", nom: "", imageUrl: '');
}
return MyUser(
id: map['id'] as String,
imageUrl: map['imageUrl'] as String? ?? '',
nom: map['nom'] as String,
);
}