It seems if it's just a variable, I can conditionally cast like this.
Animal animal = Dog();
if (animal is Dog) {
animal.bark(); // animal is of type Dog here
}
But if it's a property on a class, how do I conditionally cast?
House house = House()
house.animal = Dog();
if (house.animal is Dog) {
house.animal.bark(); // fail
}
I know I can do it like this
if (house.animal is Dog) {
Dog animal = house.animal;
animal.bark();
}
But that seems cumbersome. Is there anyway I can check and cast type in one go like I can with variables?
Thanks a lot.
This is a Dart limitation. You can check the reason in this issue (thanks, jamesdlin).
Instantiating the Animal
subclass inside each if
block can be cumbersome, in case you have lots of conditions.
I would do, instead:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With