Reputation: 2927
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 ?
Upvotes: 20
Views: 17444
Reputation: 81
what you can do is :
const dynamic a = Dodo; // or dynamic a = Dodo;
var b = new a();
b.hello();
This works fine for me; enjoy!
Upvotes: -3
Reputation: 2971
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();
Upvotes: 29
Reputation: 4415
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.
Upvotes: 7