How to discern if an optional named parameter in dart was given?

Viewed 1402

I am implementing a redux store where I treat the store as immutable. Therefore the store looks something like this:

class State {
  final String firstname;
  final String lastname;

  State(this.firstname, this.lastname);

  State.initial()
      : this.firstname = null,
        this.lastname = null;

  State copy({String firstname, String lastname}) => 
    new State(firstname ?? this.firstname, lastname ?? this.lastname);
}

This all works fine and I can copy the State and replace individual fields within the copy.

state.copy(firstname: "foo");

but now I can't set a field back to null of course.

state.copy(firstname: null); 

doesn't work.

I also tried something like:

State copy({String firstname = this.firstname, String lastname = this.lastname}) => ...

but Dart does not allow non const as default values.

3 Answers

Solution

class Dog{
  final String name;
  final int age;
  Dog({this.name, this.age});
  
  Dog.fromMap(Map<String, dynamic> map): 
    name = map['name'] as String, age = map['age'] as int;
  Map<String, dynamic> toMap() => {'name': name, 'age': age};
  
  Dog copyWith(Map<String, dynamic> fields){
    var newObj = this.toMap();
    for (final field in fields.entries)
      newObj[field.key] = field.value;
    return Dog.fromMap(newObj);
  }
}

void main() {
  Dog buddy = Dog(name: 'Buddy', age: 12);
  Dog puppy = buddy.copyWith({'age': null});
  
  // OUTPUT=> Name: Buddy Age: null
  print('Name: ${puppy.name} Age: ${puppy.age}');
}
Related