I need to make a downcasting in dart. It is possible for example from Object to int, but I'm not being able to do it with my own classes. Am I doing something wrong? or how is the correct way to do it?
class Person {
final String name;
final int age;
Person(this.name, this.age);
}
class CoolPerson extends Person {
CoolPerson(String name, int age): super(name, age);
int someFunction() {
return name.length * age;
}
}
main() {
Object x = 42;
int i = x as int;
print('Im $i');
Person person = Person('Peter', 30);
CoolPerson coolPerson = person as CoolPerson;
print('Im ${coolPerson.name}');
}
The result of this code is:
Im 42
Uncaught Error: TypeError: Instance of 'Person': type 'Person' is not a subtype of type 'CoolPerson'
It would be better to just create a CoolPerson from the start. Otherwise, it's not possible to cast person as CoolPerson;. A workaround would be creating a CoolPerson from person.
Person person = Person('Peter', 30);
CoolPerson coolPerson = CoolPerson(person.name, person.age);
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