How to get all subclasses of a class in Dart?


For given example:

class Base {
    static abstract void foo();

class ChildA extends Base{
    static void foo(){};

class ChildB extends Base{
    static void foo(){};

I would like to find all subclasses of “Base” (to call foo on each).
I need to find this at build time (run time not required).
Only idea I have is to use reflections. But i don’t know how to access class from ClassMirror?

This is what i have so far:

final mirror = currentMirrorSystem();
mirror.libraries.forEach((uri, libMirror) {
    libMirror.classes.forEach((name, ClassMirror classMirror) {
        try {
            while ((classMirror = classMirror.superclass) != null) {
                if (MirrorSystem.getName(classMirror.qualifiedName) == ".Base") {
                    //this is the classMirror of class i want
                    //but i have no idea how to access it 
                    //or how to call foo() on it

        } catch(e) {

As mentioned I don’t need this at run time so maybe a totally different approach would solve this problem. If not, question is: how do I call foo()?

thanks in advance.


Sorry guys, maybe SO related feature works better than search or maybe my research was not hard enough but anyhow I have found this:

Find all subclasses in dart

Answers there also suggested to use mirrors.
So to answer my own question a way to call static method foo is to use invoke method:

classMirror.invoke(#foo, []);

But this still is probably not an optimal solution, maybe there is a better way to do this at build time?

Answered By – fsw

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.