Home > Enterprise >  Dart create instance from list of types
Dart create instance from list of types

Time:07-25

How can I create an instance of a class knowing the index of the required class in a list? I have:

final List<Type> classTypes = [ClassA, ClassB];

How can I use something like:

var inst = classTypes[0](); // ClassA instance`

CodePudding user response:

You would have to use mirrors in order to do this. But keep in mind that mirrors is only supported when running on the dart vm, and will not work in flutter for example.

import 'dart:mirrors' as mirrors;

void main() {
  final List<Type> classTypes = [ClassA, ClassB];
  var inst = mirrors
      .reflectClass(classTypes[0])
      .newInstance(Symbol.empty, []).reflectee;
  print(inst);
}

class ClassA {}
class ClassB {}

An alternative that doesn't rely on mirrors would be to instead populate the list with constructor functions.

void main() {
  final List<dynamic Function()> classConstructors = [ClassA.new, ClassB.new];
  var inst = classConstructors[0]();
  print(inst);
}

class ClassA {}
class ClassB {}
  • Related