如何通过将 Map 解析为构造函数来创建对象?
How to create object by parsing a Map to constructor?
在 Dart 中,是否可以通过将映射解析为构造函数来创建对象?
示例:
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);
通过创建工厂:
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,
);
}
在 Dart 中,是否可以通过将映射解析为构造函数来创建对象?
示例:
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);
通过创建工厂:
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,
);
}