简体   繁体   中英

What is this unary postfix in dart/flutter?

i saw this unary postfix in Dart/flutter code: ?.

like this:

videoController?.dispose();

and i want to know how it work...

This is a great feature in Dart

meaning is if and only if that object is not null otherwise, return null .

Simple example:

void main() {
  Person p1 = new Person("Joe");
  print(p1?.getName); // Joe

  Person p2;
  print(p2?.getName); // null

  //print(p2.getName); // this will give you an error because you cannot invoke a method or getter from a null
}

class Person {
  Person(this.name);
  String name;

  String get getName => name;
}

There are other cool null aware operators like ?? . Read my QnA to find out more about null-aware operators.

It tests for null,

https://www.dartlang.org/guides/language/language-tour

"?. Conditional member access Like ., but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)"

It is a null-aware operator . It is the short form of the following.

Code

 ((obj) => obj == null ? null : x.method())(object)
 // is equal to
 object?.method()

You can find out more about null-aware operators here .

Explanation

Reads as:

  • Only execute method if object is not null

  • If object is null return null (otherwise evaluation from method )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM