thumbnail

Conditional Member Access Operator In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Conditional member access operator is used for safely accessing members of objects that can be null.

Program using Conditional member access operator

class Person {
  String name;
}

main(List<String> args) {
  Person p;
  print('p is ${p}');
  // notice that p is null,
  // still we can access the name member of Person class with no error using
  // the conditional access operator
  // because p is null p?.name returns null
  var name = p?.name;
  print(name);

  // initializing variable p
  p = Person();
  // defining p.name
  p.name = 'hello';

  // when p.name is defined, ?. operator behaves like a regular member access operator
  name = p?.name;
  print(name);
}

Above program produces following output:

p is null
null
hello

As shown in above program, we can safely access members of objects that are not initialized using the conditional access operator.

If the operand is null, then conditional member access operator returns null, otherwise it works as regular member access operator.