我正在尝试为我的类创建一个“copyWith”方法,它适用于大多数场景。
问题是当我尝试将可为 null 的属性设置为 null 时,因为我的函数无法识别它是否是有意的。
前任。:
class Person {
final String? name;
Person(this.name);
Person copyWith({String? name}) => Person(name ?? this.name);
}
void main() {
final person = Person("Gustavo");
print(person.name); // prints Gustavo
// I want the name property to be nul
final person2 = person.copyWith(name: null);
print(person2.name); // Prints Gustavo
}
Run Code Online (Sandbox Code Playgroud)
有谁知道这种情况的一些解决方法?这真的很困扰我,我不知道如何避免这种情况。