Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

flutter - Dart 2.1.0 smart cast using 'is' not working

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

import 'package:meta/meta.dart'

@immutable
abstract class UiState {}

class Loading extends UiState {}

class Success extends UiState {
  Success(this.message);

  final String message;
}

class Failure extends UiState {}

I try to use a UiState as follows:

class MyWidget extends StatelessWidget {
  const MyWidget({
    Key key,
    @required this.uiState,
  }) : super(key: key);

  final UiState uiState;

  Widget build(BuildContext context) {
    if (uiState is Success) {
      return Text(uiState.message);
    }
    ...
  }
}

But VSCode tells me that "The getter 'message' isn't defined for the class 'UiState'".

I've used smart casts before and they did work. But in this instance, I'm not able to figure out why it's not working.

My pubspec has the following:

environment:
  sdk: ">=2.1.0 <3.0.0"

So, I assume my dart version is atleast 2.1.0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...