1

Assume I have some Type instances:

final strType = String;
final intType = int;

I want to initialize instances of the Types, for example, preferably,

final myString = strType(); // myString is String()

or

final myInt = new intType(); // myInt is int()

However, the compiler raised an error of strType isn't a function.

Is it possible to initialize an instance of a Type in Dart?

1 Answer 1

2

This is not possible at the language level. It is possible with reflection, but the code will be complex and to use it on the web or flutter it would require codegen.

Instead of assigning a Type to a variable, consider assigning a function type. () => SomeClassName() is an anonymous function that can create an instance of SomeClassName.

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.