Yousif khalid
Yousif khalid

Reputation: 6465

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

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):....
}

Upvotes: 11

Views: 6648

Answers (2)

Wendel
Wendel

Reputation: 2977

I had a same problem to "casting". The Dart solution is use "as" like this:

B b = A() as B;

Dart: Docs: Fixing common type problems

Upvotes: 6

Pieter van Loon
Pieter van Loon

Reputation: 5648

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

Upvotes: 4

Related Questions