
Member-only story
FLUTTER INTERVIEW QUESTIONS
What are ??, ??=, ?., …? in Dart?
Looking weird, don’t they?
Those are null-aware operators in Dart and they tend to shorten your code a lot.
??
Called also null operator. This operator returns expression on its left, except if it is null, and if so, it returns right expression:
void main() {
print(0 ?? 1); // <- 0
print(1 ?? null); // <- 1
print(null ?? null); // <- null
print(null ?? null ?? 2); // <- 2
}
??=
Called also null-aware assignment. This operator assigns value to the variable on its left, only if that variable is currently null:
void main() {
int value;
print(value); // <- null
value ??= 5;
print(value); // <- 5, changed from null
value ??= 6;
print(value); // <- 5, no change
}
?.
Called also null-aware access(method invocation). This operator prevents you from crashing your app by trying to access a property or a method of an object that might be null:
void main() {
String value; // <- value is null
print(value.toLowerCase()); // <- will crash
print(value?.toLowerCase().toUpperCase()); // <- will crash
print(value?.toLowerCase()?.toUpperCase()); // <- output is null
}
…?
Called also null-aware spread operator. This operator prevents you from adding null elements using spread operator(lets you add multiple elements into your collection):
void main() {
List<int> list = [1, 2, 3];
List<String> list2; // <- list2 is null
print(['chocolate', ...?list2]); // <- [chocolate]
print([0, ...?list2, ...list]); // <- [0, 1, 2, 3]
print(['cake!', ...list2]); // <- will crash
}
?
And for bonus, ? operator.
Looking similar to those we already saw, this is NOT a null-aware operator, but a ternary one. Ternary operator is used across many languages, so you should be…