dartdart-null-safety

Dart: Custom "copyWith" method with nullable properties


I'm trying to create a "copyWith" method for my class, and it works with most scenarios.

The problem is when I try to set a nullable property to null, because my function cannot recognize whether it's intentional or not.

Ex.:

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
}

Does anyone knows some workaround for this situation? This is really bothering me and I don't know how to avoid this situation.


Solution

  • Inspired by @jamesdlin answer:

    All you need to do is provide a wrapper around. Take this example in consideration:

    class Person {
      final String? name;
    
      Person(this.name);
    
      Person copyWith({Wrapped<String?>? name}) =>
          Person(name != null ? name.value : this.name);
    }
    
    // This is all you need:
    class Wrapped<T> {
      final T value;
      const Wrapped.value(this.value);
    }
    
    void main() {
      final person = Person('John');
      print(person.name); // Prints John
    
      final person2 = person.copyWith();
      print(person2.name); // Prints John
    
      final person3 = person.copyWith(name: Wrapped.value('Cena'));
      print(person3.name); // Prints Cena
    
      final person4 = person.copyWith(name: Wrapped.value(null));
      print(person4.name); // Prints null
    }