飞镖/颤振中的一元后缀是什么?

时间:2018-07-03 14:59:16

标签: dart flutter postfix-notation unary-operator

我在Dart / flutter代码中看到了这个一元后缀:?.

像这样:

videoController?.dispose();

我想知道它是如何工作的...

3 个答案:

答案 0 :(得分:2)

这是Dart的一项重要功能

的含义是,并且仅当该对象不为null时,否则返回null

简单的例子:

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;
}

还有其他一些很酷的空感知运算符,例如??Read my QnA来查找有关空感知运算符的更多信息。

答案 1 :(得分:1)

它测试是否为空,

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

“?.。条件成员访问与。类似,但最左边的操作数可以为null;例如:foo?.bar从表达式foo中选择属性bar,除非foo为null(在这种情况下foo?.bar的值为null) “

答案 2 :(得分:1)

它是 空感知 运算符。这是以下内容的简短形式。

代码

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

您可以找到更多的about null-aware operators here

说明

读取为:

  • 如果method不是object

  • ,则仅执行null
  • 如果objectnull,则返回null(否则来自method的求值)