如何有条件地在飞镖中投射类型?

hgl*_*hgl 5 casting dart

似乎如果它只是一个变量,我可以像这样有条件地进行转换。

Animal animal = Dog();
if (animal is Dog) {
  animal.bark(); // animal is of type Dog here
}
Run Code Online (Sandbox Code Playgroud)

但是如果它是一个类的属性,我如何有条件地转换?

House house = House()
house.animal = Dog();
if (house.animal is Dog) {
  house.animal.bark(); // fail
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做

if (house.animal is Dog) {
  Dog animal = house.animal;
  animal.bark();
}
Run Code Online (Sandbox Code Playgroud)

但这似乎很麻烦。无论如何,我可以像使用变量一样一次性检查和转换类型吗?

非常感谢。

Hug*_*sos 6

这是 Dart 限制。您可以在此问题中查看原因(谢谢,jamesdlin)。

在有很多条件的情况下,在Animal每个if块内实例化子类可能很麻烦。

我会这样做,而不是:

final house = House()..animal = Dog();
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}
Run Code Online (Sandbox Code Playgroud)