Smart cast (automatic type promotion) using ‘is’ is not working

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 be overridden by derived class and which could return different values from one access to the next.

Also see:

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

Note that this also applies to type promotion from nullable to non-nullable types, such as when doing if (someNullableVariable != null).

Also see https://dart.dev/tools/non-promotion-reasons for some other reasons why automatic type promotion might not occur.

Leave a Comment