15

It is possible to pass a class type as a variable in Dart ?

I am trying to do something as follows:

class Dodo
{
  void hello() {
    print("hello dodo");
  }
}

void main() {

var a = Dodo;
var b = new a();
b.hello();

}

in python similar code would work just fine. In Dart I get an error at new a() complaining that a is not a type.

Is is possible to use class objects as variables ? If not, what is the recommended work around ?

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
rodrigob
  • 2,699
  • 2
  • 27
  • 33

2 Answers2

23

ANother way to do it is by passing a closure rather than the class. Then you can avoid using mirrors. e.g.

a = () => new Dodo();
...
var dodo = a();
Alan Knight
  • 2,191
  • 1
  • 11
  • 13
  • 3
    Note that such solution, while very useful, may not be so elegant in case you had many parameters to pass. – Smily Nov 03 '19 at 22:02
  • Why not? You could just do something like: `a = (String myString) => new Dodo(myString);` and then `var dodo = a("hello");` – Ian Spryn Aug 21 '20 at 14:16
7

You can use the mirrors api:

import 'dart:mirrors';

class Dodo {
  void hello() {
    print("hello dodo");
  }
}

void main() {
  var dodo = reflectClass(Dodo);

  var b = dodo.newInstance(new Symbol(''), []).reflectee;
  b.hello();
}

Maybe it can be written more compact, especially the new Symbol('') expression.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
Ozan
  • 4,235
  • 2
  • 20
  • 35