使用'is'的Dart 2.1.0 Smart Cast无法正常工作 [英] Dart 2.1.0 smart cast using 'is' not working

查看:50
本文介绍了使用'is'的Dart 2.1.0 Smart Cast无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bloc模式,并具有以下代码来定义我的状态:

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 {}

我尝试如下使用 UiState :

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);
    }
    ...
  }
}

但是VSCode告诉我,未为类'UiState'定义getter'消息'".

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.

我的pubspec具有以下内容:

My pubspec has the following:

environment:
  sdk: ">=2.1.0 <3.0.0"

所以,我认为我的dart版本至少为2.1.0.

So, I assume my dart version is atleast 2.1.0.

推荐答案

is 仅对局部变量执行隐式类型提升.

is performs implicit type promotion only for local variables.

对于局部变量,编译器可以推断出在使用 is 检查其类型与使用该变量之前之间,该局部变量的类型不会改变.

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.

对于非局部变量,编译器无法轻松地保证这一点.非局部变量隐式提供getter函数,该函数可以被派生类覆盖,并且可以从一次访问返回另一次访问的不同值.

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.

另请参阅:

作为显式强制转换的替代方法,您当然可以先将非局部变量存储在局部变量中.例如:

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

这篇关于使用'is'的Dart 2.1.0 Smart Cast无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆