TSR
TSR

Reputation: 20597

differentiate undefined and null in Dart

Consider the following function:

 BasicClass copyWith({
    String id,
  }) {
   // some code behaving differently for 1) id is undefined and 2) id is explicit null
  }

And consider the two parameters below:

  1. Nothing (id is undefined)

    copyWith();

  2. Null (id is null)

    copyWith(id: null);

in the copyWith method, is there any way I can make it behave differently for 1) and 2)

Upvotes: 12

Views: 2903

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277517

There is no way to differentiate null from "no parameter passed".

The only workaround (which is used by Freezed to generate a copyWith that supports null) is to cheat using a custom default value:

final undefined = Object();

class Example {
  Example({this.param});
  final String param;

  Example copyWith({Object param = undefined}) {
    return Example(
      param: param == undefined ? this.param : param as String,
    );
  }
}

This requires typing your variables as Object though.

To fix that issue, you can use inheritance to hide the Object under a type-safe interface (again, see Freezed):

final undefined = Object();

class Example {
  Example._();
  factory Example({String param}) = _Example;
  
  String get param;

  void method() {
    print('$param');
  }

  Example copyWith({String param});
}

class _Example extends Example {
  _Example({this.param}): super._();

  final String param;

  @override
  Example copyWith({Object param = undefined}) {
    return Example(
      param: param == undefined ? this.param : param as String,
    );
  }
}

Upvotes: 9

Related Questions