Skip to content

Instantly share code, notes, and snippets.

@evaisse
Last active June 5, 2025 14:14
Show Gist options
  • Save evaisse/9097256c90cfc59e529254d724c5ce8f to your computer and use it in GitHub Desktop.
Save evaisse/9097256c90cfc59e529254d724c5ce8f to your computer and use it in GitHub Desktop.
copyWith with nullable and optional
/// General demonstration about the annoying way to set to null a copy of another object
///
/// @see https://github.com/dart-lang/language/issues/877
/// @see https://stackoverflow.com/questions/68009392/dart-custom-copywith-method-with-nullable-properties
class Person {
final String name;
final String? nickName;
Person({required this.name, this.nickName});
/// https://dart.dev/language/records#record-types
Person copyWith({String? name, (String?,)? nickName}) {
return Person(
name: name ?? this.name,
nickName: nickName != null ? (nickName.$1 ?? this.nickName) : null,
);
}
}
void main() {
final a = Person(name: 'Amadeus', nickName: 'Momo');
assert(a.nickName == 'Momo');
final b = a.copyWith(nickName: (null));
assert(b.nickName == null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment