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`
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 {}
Types generally aren't usable for much. You instead could have aListof 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.