Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart – Get result from a method invoked using reflection

I’m trying to use dart’s mirror API to dynamically invoke a function.

How can I obtain the result that’s returned from the doWork method when invoking it via an InstanceMirror

class MyData {
  String someString;
}

class MyService {
  Future<MyData> doWork() async {
    print('doing work');
    return await Future(() => MyData()..someString = 'my result');
  }
}
void main() async {
  var instance = MyService();
  var mirrror = reflect(instance);
  var result = mirrror.invoke(#doWork, []);
}

I can see that "doing work" gets printed to the console so I know it’s being invoked, but I’m struggling to interpret the result from the invoke function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The value are inside the InstanceMirror in the property reflectee. So something like this:

import 'dart:mirrors';

class MyData {
  String? someString;
}

class MyService {
  Future<MyData> doWork() async {
    print('doing work');
    return await Future(() => MyData()..someString = 'my result');
  }
}
void main() async {
  var instance = MyService();
  var mirrror = reflect(instance);
  var result = mirrror.invoke(#doWork, <dynamic>[]);
  var resultValue = await (result.reflectee as Future<MyData>);
  print(resultValue.someString); // my result
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading