Search code examples
dartflutterpostfix-notationunary-operator

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...


Solution

  • 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.