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

1,627

Solution 1

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

Solution 2

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

Share:
1,627
Yousif khalid
Author by

Yousif khalid

Mobile Application Developer with 7+ years of experience Computer-Aided Design and Manufacturing graduate. I do a lot of Android stuff, I developed Grid Drawing, Iraqi Exchange, Iraq News, Handwriting, and many other applications. I'm now Flutter Developer (Mobile and Web) As an engineer, bringing skills like mechanical design, electronic circuits + PCBs design, embedded systems design, automation programming and manufacturing together.

Updated on December 14, 2022

Comments

  • Yousif khalid
    Yousif khalid over 1 year

    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):....
    }
    
  • Yousif khalid
    Yousif khalid over 3 years
    Thanks, I need a way to do that?
  • Pieter van Loon
    Pieter van Loon over 3 years
    Could you then add a more concrete version of what you want to do (so the concept and maybe some actual code).