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:
Nothing (id is undefined)
copyWith();
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)
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.
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.
The three null-aware operators that Dart provides are ?. , ?? , and ??= .
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.
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,
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With