Dynamic class method invocation in Dart

大憨熊 提交于 2019-11-28 12:11:51
Kai Sellgren

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?

You can use Dart Mirror API to do such thing. Mirror API is not fully implemented now but here's how it could work :

import 'dart:mirrors';

class Page {
  String name;
}

main() {
  final page = new Page();
  var value = "value";

  InstanceMirror im = reflect(page);
  im.setField("name", value).then((_){
    print(page.name); // display "value"
  });
}

You can use Serializable

For example:

import 'package:serializable/serializable.dart';

@serializable
class Page extends _$PageSerializable {
  String name;
}

main() {
  final page = new Page();
  var attribute = "name";
  var value = "value";

  page["name"] = value;
  page[attribute] = value;

  print("page.name: ${page['name']}");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!