Dart 2.1.0 smart cast using 'is' not working

前端 未结 1 1343
别跟我提以往
别跟我提以往 2020-12-21 10:03

I\'m using the Bloc pattern and have the following code to define my states:

import \'package:meta/meta.dart\'

@imm         


        
相关标签:
1条回答
  • 2020-12-21 10:13

    is performs implicit type promotion only for local variables.

    For a local variable, the compiler can deduce that the type of the local variable will not be change between the time that its type is checked with is and before the variable is used.

    For a non-local variable, the compiler cannot easily make that guarantee. Non-local variables implicitly provide getter functions, which could return different values from one access to the next.

    Also see:

    • https://github.com/dart-lang/sdk/issues/21530
    • https://github.com/dart-lang/sdk/issues/34480

    As an alternative to an explicit cast, you of course could store the non-local variable in a local variable first. For example:

    void memberFun() {
      final emp = _emp;
      if (emp is Person) {
        emp.firstName = 'Bob';
      }
    }
    
    0 讨论(0)
提交回复
热议问题