Dart 2.1.0 智能转换使用“is"不起作用 [英] Dart 2.1.0 smart cast using 'is' not working

查看:13
本文介绍了Dart 2.1.0 智能转换使用“is"不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 '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.

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

另见https://dart.dev/tools/non-promotion-reasons 可能不会发生自动类型提升的其他一些原因.

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

这篇关于Dart 2.1.0 智能转换使用“is"不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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