Dynamic class method invocation in Dart

2019-01-19 17:12发布

Like the question at Dynamic class method invocation in PHP I want to do this in Dart.

var = "name";
page.${var} = value;
page.save();

Is that possible?

3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-19 17:52

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']}");
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-19 18:03

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?

查看更多
迷人小祖宗
4楼-- · 2019-01-19 18:14

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"
  });
}
查看更多
登录 后发表回答