How to cast a parent class to its child class in Dart

Viewed 2876

I have two classes A and B extend A.

class A{
  String a;
  A();
}
class B extends A{
  String b;
  B();
}

How to getA Like:

B getA(){
  return A();
}

Or

  B b = A();

My Code :

  Future<B> getB() async {
    return apiMethod("url", headers: {'requirestoken': true}, httpEnum: HttpEnum.GET).then((response) {
      return B.fromJson(response.data);
    }).catchError((error, stacktrace) => A.catchErrorMethod(error, stacktrace));
  }

While class A

class A {
  A.catchErrorMethod(error, stacktrace):....
}
2 Answers

You cannot do this. B is an A but A is not a B.

However you can simply use B everywhere as if it was an A

Related