Null check doesn't cause type promotion in Dart

前端 未结 1 667
无人共我
无人共我 2021-01-23 13:37

I\'m upgrading a personal package that is based on the Flutter framework. I noticed here in the Flutter Text widget source code that there is a null check:



        
相关标签:
1条回答
  • 2021-01-23 14:13

    Dart engineer Erik Ernst says on GitHub:

    Type promotion is only applicable to local variables. ... Promotion of an instance variable is not sound, because it could be overridden by a getter that runs a computation and returns a different object each time it is invoked. Cf. dart-lang/language#1188 for discussions about a mechanism which is similar to type promotion but based on dynamic checks, with some links to related discussions.

    So local type promotion works:

      String myMethod(String? myString) {
        if (myString == null) {
          return '';
        }
        
        return myString;
      }
    

    But instance variables don't promote. For that you need to manually tell Dart that you are sure that the instance variable isn't null in this case by using the ! operator:

    class MyClass {
      String? _myString;
      
      String myMethod() {
        if (_myString == null) {
          return '';
        }
        
        return _myString!;
      }
    }
    
    0 讨论(0)
提交回复
热议问题