0

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`
1
  • 1
    You can't. What if the types don't have an unnamed constructor? What if they require arguments? Types generally aren't usable for much. You instead could have a List of callbacks (e.g. [ClassA.new, ClassB.new, () => ClassC.namedConstructor(fixedArgument)]). Note that this would forgo static type-safety for the returned object, but you can't statically type-check that anyway since it's inherently a dynamic operation. Commented Jul 24, 2022 at 23:03

1 Answer 1

1

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 {}
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.