How to conditionally cast a type in dart?
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();}
You can manage a conditional type cast like the example below:
class MyException implements Exception { int customCode = 2;}void myFunc(){ //you can switch between the values below to see the effect // throw Exception(); throw MyException();}void main() { try { myFunc(); } catch (e) { final i = e is MyException ? e.customCode : -10; print(i); }}