Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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.

like image 771
Fabian Avatar asked Nov 28 '17 20:11

Fabian


1 Answers

You can use a special marker in the file like this

const _noValueGiven = const Object();

class State {
  ...
  State copy({String firstName: _noValueGiven, String lastName: _noValueGiven}) {
    if (identical(firstName, _noValueGiven)) {
      firstName = this.firstName;
    }
    ...
  }
}
like image 120
Harry Terkelsen Avatar answered Sep 25 '22 23:09

Harry Terkelsen