2

in Dart, you can assign a class to a variable, eg,

var klass = String;

but once assigned, how do you used it?

var str = new klass(); ===> ERROR: malformed type used

once one has a class in a variable, how does one use it to instantiate a new object of that class?

1 Answer 1

3

You have to use dart:mirrors.

import 'dart:mirrors';

class A {
  A();
  A.named(String value);
}

main() {
  final t = A;

  // same as 'new A()'
  final a1 = reflectClass(t).newInstance(const Symbol(''), []).reflectee;

  // same as 'new A.named('test')'
  final a2 = reflectClass(t).newInstance(#named, ['test']).reflectee;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.