How to dynamically create a method or a setter in a class in Dart?

dart

Solution

No, you can't add a real member to a class.

I said real member because you can simulate such feature with noSuchMethod(). Here a example :

@proxy
class A {
  final dynamicMethods = <Symbol, Function>{};

  noSuchMethod(Invocation i) {
    if (i.isMethod && dynamicMethods.containsKey(i.memberName)) {
      return Function.apply(dynamicMethods[i.memberName],
          i.positionalArguments, i.namedArguments);
    }
    return super.noSuchMethod(i);
  }
}

main() {
  final a = new A();
  a.dynamicMethods[#sayHello] = () => print('hello');
  a.sayHello();
}

In the future this could perhaps be possible. See this excerpt from the article on Mirrors :

We’d like to support more powerful reflective features in the future. These would include mirror builders, designed to allow programs to extend and modify themselves, and a mirror-based debugging API as well.

Problem

Is it possible to dynamically add an instance method or a setter to an existing class, either from within this class or from outside of it?

Original source