15

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
  • 396
  • 2
  • 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
  • 506
  • 8
  • 25
Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
  • 6
    Is anyone know how to do this in Flutter? In flutter we cannot import dart:mirros package :/ – Kavinda Jayakody Jan 12 '20 at 08:42
  • 1
    @KavindaJayakody Flutter forbids using mirrors and html libraries from Dart due to performance premise, using them would drastically impact widget rebuild time. You can read more about this [at Flutter FAQ page](https://docs.flutter.dev/resources/faq#does-flutter-come-with-a-reflection--mirrors-system). – Stahp Oct 07 '22 at 11:12
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
  • 506
  • 8
  • 25
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 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,466
  • 2
  • 15
  • 32