If I know the name of a function, is it possible to get its parameters?

Issue

Dart code:

void hello(String name) {
    print(name);
}

main() {
    var funcName = "hello";
    // how to get the parameter `String name`?
}

Using the function name as a string, "hello", is it possible to get the parameter String name of the real function hello ?

Solution

You can use mirrors to do that.

import 'dart:mirrors';

void hello(String name) {
    print(name);
}

main() {
  var funcName = "hello";

  // get the top level functions in the current library
  Map<Symbol, MethodMirror> functions = 
      currentMirrorSystem().isolate.rootLibrary.functions;
  MethodMirror func = functions[const Symbol(funcName)];

  // once function is found : get parameters
  List<ParameterMirror> params = func.parameters;
  for (ParameterMirror param in params) {
    String type = MirrorSystem.getName(param.type.simpleName);
    String name = MirrorSystem.getName(param.simpleName);
    //....
    print("$type $name");
  }
}

Answered By – Alexandre Ardhuin

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.