ivnsch / dart_copy_with_plugin

Dart copyWith generation plugin
MIT License
8 stars 0 forks source link

Force value to null #1

Closed jaumard closed 5 years ago

jaumard commented 5 years ago

Problem with this kind of copyWith methods is that you can force a value to null if it exist on the object already, it will always take the existing value, so not the wanted behavior ^^

But great work with the plugin !

ivnsch commented 5 years ago

Thanks! You mean the case where you want to set the fields to null? If yes, it's possible by passing the optional in a wrapper, e.g:

Person copyWith({Nullable<int> age, Nullable<String> name}) {
  return new Person(
    age: age == null ? this.age : age.value,
    name: name == null ? this.name : name.value,
  );
}

Where

class Nullable<T> {
  T _value;

  Nullable(this._value);

  T get value {
    return _value;
  }
}

(See https://github.com/brianegan/flutter_redux/issues/40)

In my experience (with other langs) this is used rarely though and in these cases you can just edit the generated code!

I can also imagine that the plugin could solve this, by showing a dialog where you can select if you want the fields to be optional and an input for the name of your wrapper class. But the effort is probably not justified.