14

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?

Community
  • 1
  • 1
samer.ali
  • 386
  • 1
  • 3
  • 11

3 Answers3

16

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?

Ramin Firooz
  • 496
  • 8
  • 22
Kai Sellgren
  • 23,990
  • 8
  • 69
  • 83
7

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"
  });
}
Ramin Firooz
  • 496
  • 8
  • 22
Alexandre Ardhuin
  • 62,400
  • 12
  • 142
  • 126
  • 1
    The call to `Futures.wait()` makes little sense here. You can omit it and the result is the same. `Futures.wait()` returns a `Future` that completes when the given actions complete, so, you really have to write a `.then()` to get it properly to work. Of course it now works by luck since the operations happen to be non-async :) – Kai Sellgren Nov 08 '12 at 17:43
  • Thanks for your comment. I am new to Future usage and I confused with the `await` proposal www.dartbug.com/104 – Alexandre Ardhuin Nov 08 '12 at 18:07
3

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']}");
}
Luis Vargas
  • 2,376
  • 2
  • 13
  • 30