Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a class type as a variable in Dart

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 ?

like image 485
rodrigob Avatar asked Apr 15 '14 20:04

rodrigob


People also ask

How do you pass a Dart class?

what you can do is : const dynamic a = Dodo; // or dynamic a = Dodo; var b = new a(); b. hello();

How do you get variable type in Dart?

Dart objects have runtimeType property which returns Type . To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .


2 Answers

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();
like image 119
Alan Knight Avatar answered Sep 28 '22 05:09

Alan Knight


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.

like image 22
Ozan Avatar answered Sep 28 '22 03:09

Ozan