Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class method invocation in Dart

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?

like image 301
samer.ali Avatar asked Nov 08 '12 16:11

samer.ali


3 Answers

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']}");
}
like image 57
Luis Vargas Avatar answered Nov 12 '22 16:11

Luis Vargas


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?

like image 26
Kai Sellgren Avatar answered Nov 12 '22 17:11

Kai Sellgren


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"
  });
}
like image 7
Alexandre Ardhuin Avatar answered Nov 12 '22 16:11

Alexandre Ardhuin