Sdk: how to call class method with string function name?

Created on 24 Oct 2018  路  4Comments  路  Source: dart-lang/sdk

example:
class A {
B(){
return true;
}
C(){
return false;
}
}

var str = "B";
how to call function B with str;

type-question

Most helpful comment

The general problem requires reflection, so you can only do it using the dart:mirrors library. That library is not available on all platforms (it's not on the web and not in Flutter).

Short of that, you need to know the possible methods ahead of time, and then you can either write a function like:

Function getMember(A object, String name) {
   if (name == "B") return object.B;
   if (name == "C") return object.C;
   throw ArgumentError.value(name, "name");
}

or use something like package:reflectable to generate the function for you.

All 4 comments

The general problem requires reflection, so you can only do it using the dart:mirrors library. That library is not available on all platforms (it's not on the web and not in Flutter).

Short of that, you need to know the possible methods ahead of time, and then you can either write a function like:

Function getMember(A object, String name) {
   if (name == "B") return object.B;
   if (name == "C") return object.C;
   throw ArgumentError.value(name, "name");
}

or use something like package:reflectable to generate the function for you.

@lrhn Last two dev versions of flutter (0.9.6 and 0.10.0) stopped working when having reflectable in reflectable project dependencies. It looks like incompatible internal dependency problem:

Closing. To add to @lrhn 's explanation, mirrors is not likely to be provided for client code as it interferes with the compiler's ability to optimize code.

@linguitang, on the reflectable version issue, please see https://github.com/dart-lang/reflectable/issues/153.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

55555Mohit55555 picture 55555Mohit55555  路  3Comments

rinick picture rinick  路  3Comments

Hixie picture Hixie  路  3Comments

DartBot picture DartBot  路  3Comments

ranquild picture ranquild  路  3Comments