Dart – Null-aware operators

Null-aware operators was introduced in Dart 1.12.0. This feature helps us reduce the amount of code when working with potential nullable objects. It includes 4 operators: if null operator ( ?? ), null-aware assignment ( ??= ), null-aware access ( x?.p ) and null-aware method invocation ( x?.m() ).

1. if null operator

expr ?? otherExpr

Meaning:
– if expr is not null, use it.
– otherwise use otherExpr.

void testIfNullOperator() {
  int number;
  // number is null, use 10.
  final a = number ?? 10;
  print(a);

  // a is not null, use a.
  final b = a ?? 0;
  print(b);
}

// Output
10
10


2. null-aware assignment

x ??= expr

Meaning: assign expr to x only if x is null.

void testNullAwareAssignment() {
  int number;
  // number is null, assign 100 to number.
  number ??= 100;
  print(number);

  // number is not null, keep number as is, don't assign 200 to it.
  number ??= 200;
  print(number);
}

// Output
100
100


3. null-aware access

x?.p

Meaning:
– if x is not null, use it.
– otherwise use null.

void testNullAwareAccess() {
  String s;
  // s is null, use null.
  print(s?.length);

  s = 'Coflutter';
  // s is not null, use s.
  print(s?.length);
}

// Output
null
9


4. null-aware method invocation

x?.m()

Meaning: invoke the method m only if x is not null

void testNullAwareMethodInvocation() {
  String s;
  // s is null, don't call toUpperCase()
  print(s?.toUpperCase());

  s = 'Coflutter';
  // s is not null, call toUpperCase()
  print(s?.toUpperCase());
}

// Output
null
COFLUTTER


If you are looking for a developer or a team to build you next projects, please Drop us your request!

Tagged : /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x