Flutter 颤振:合并相同类型的对象并合并定义的属性(比如javascript?)
使用颤振和飞镖,让我们假设我有这个类:Flutter 颤振:合并相同类型的对象并合并定义的属性(比如javascript?),flutter,dart,Flutter,Dart,使用颤振和飞镖,让我们假设我有这个类: @JsonSerializable() class User { @JsonKey(nullable: true, required: false) final String name; @JsonKey(nullable: true, required: false) final int age; User({ this.name, this.age, }); factory User.fromJson(
@JsonSerializable()
class User {
@JsonKey(nullable: true, required: false)
final String name;
@JsonKey(nullable: true, required: false)
final int age;
User({
this.name,
this.age,
});
factory User.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
@override
String toString() {
return 'User ${toJson().toString()}';
}
}
导致此json表示:{name:null,age:34}
,它将覆盖服务器上已经存在的名称
我还尝试了“json合并”两个对象,一个是我已经拥有的名称
,另一个是更新年龄
的新dto:
final combined = UpdateUserRequest.fromJson({
...(dtoWithAge.toJson()),
...(existingUserWithName.toJson()),
});
但无论我如何处理这些问题,它们最终都会相互压倒
那么,是否需要获取类的json/DTO实例,该实例只包含我希望服务器更新的属性和值?(尝试实现与javascript非常相似的功能)我认为没有预先实现的解决方案。假设我理解了您试图实现的目标,那么将
copyWith
方法添加到User
中如何
User copyWith({
String name,
int age,
}) => User(
name: name ?? this.name,
age: age ?? this.age,
);
您可以这样使用它:
final existingUser = User(name: 'John');
final updatedUser = existingUser.copyWith(age: 25);
sendUpdateRequestWith(updatedUser);
为了您的方便,有一个插件来生成它
- vscode:
- IDEA/Android工作室:
final existingUser = User(name: 'John');
final updatedUser = existingUser.copyWith(age: 25);
sendUpdateRequestWith(updatedUser);