I have many objects of the same base type. I want to build a generic function to create them. Code sample :
class Grid extends Display { ....
class Start extends Display { ....
class MainClass {
Grid grid;
Start start;
....
}
in a MainClass method, instead of this :
start = new Start();
start.load(PATH);
grid = new Grid();
grid.load(PATH);
....
I would like to do something like this :
void _newDisplay(dynamicType, Display display) {
display = new dynamicType();
display.load(PATH);
}
_newDisplay(Start, start);
_newDisplay(Grid, grid);
....
I read http://www.dartlang.org/articles/optional-types/ but did not find exactly what I wanted.
I also found Instantiate a class from a string but there is a comment saying : "Note: this might not work when compiled to JavaScript. The dart2js compiler doesn't yet fully support mirrors.". Is this "mirror" solution the only one available to make dynamic instantiation ?
Dart doesn't support a direct way to do this. Usually we work around this by providing a closure that instantiates the type for us:
void _newDisplay(dynamicType, Display display) {
display = dynamicType();
display.load(PATH);
}
_newDisplay(() => Start(), start);
_newDisplay(() => Grid(), grid);
Also see What are some good workarounds for dart's lack of static typing semantics?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With