Flutter - How to instantiate an object from a Type
You cannot create an instance of a class from a Type
object representing the class, at least not without mirrors (and neither the Flutter nor the web platform supports mirrors).
You cannot tear-off a constructor (yet, I hope we'll add that feature at some point), so the option of creating a static helper function which calls the constructor, and passing the helper function around, is the best current solution.
If you know the number of arguments required by such a function, you don't need to use Function.apply
, you can just call it directly.
You can tear-off a function if you don't add the parentheses ()
. You don't need dart:mirror
.
void main() {
// Tear off a global function
Function myFunction = MyClass.someStaticFunction;
// Call it statically
myFunction('arg');
// Call it dynamically
Function.apply(myFunction, ['arg']);
// Tear it off with a precise Function Type
void Function(String) myFunction2 = MyClass.someStaticFunction;
}
class MyClass {
static void someStaticFunction(String someArg) {
print('someStaticFunction $someArg');
}
}