dartdart-mirrors

Dynamic class method invocation in Dart


Like the question at Dynamic class method invocation in PHP I want to do this in Dart.

var = "name";
page.${var} = value;
page.save();

Is that possible?


Solution

  • There are several things you can achieve with Mirrors.

    Here's an example how to set values of classes and how to call methods dynamically:

    import 'dart:mirrors';
    
    class Page {
      var name;
    
      method() {
        print('called!');
      }
    }
    
    void main() {
      var page = new Page();
    
      var im = reflect(page);
    
      // Set values.
      im.setField("name", "some value").then((temp) => print(page.name));
    
      // Call methods.
      im.invoke("method", []);
    }
    

    In case you wonder, im is an InstanceMirror, which basically reflects the page instance.

    There is also another question: Is there a way to dynamically call a method or set an instance variable in a class in Dart?