Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differentiate undefined and null in Dart

Tags:

flutter

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)

like image 339
TSR Avatar asked Sep 16 '20 22:09

TSR


People also ask

What is the difference between null and undefined?

Definition: Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler.

Is there undefined in Dart?

Undefined means "no value", null means "value equivalent to emptiness". In Dart however (and possibly in other languages, I don't know, but right now I'm using Dart), there is no undefined, only null. Therefore it is impossible to make the distinction between a value equivalent to emptiness and the absence of value.

What are the different null operators in Dart?

The three null-aware operators that Dart provides are ?. , ?? , and ??= .

What is the difference between null and undefined in typescript?

A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined.


1 Answers

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,
    );
  }
}
like image 91
Rémi Rousselet Avatar answered Oct 10 '22 09:10

Rémi Rousselet