Let's assume that an initialization of MyComponent in Dart requires sending an HttpRequest to the server. Is it possible to construct an object synchronously and defer a 'real' initialization till the response come back?
In the example below, the _init() function is not called until "done" is printed. Is it possible to fix this?
import 'dart:async';
import 'dart:io';
class MyComponent{
MyComponent() {
_init();
}
Future _init() async {
print("init");
}
}
void main() {
var c = new MyComponent();
sleep(const Duration(seconds: 1));
print("done");
}
Output:
done
init
A constructor can only return an instance of the class it is a constructor of (
MyComponent
). Your requirement would require a constructor to returnFuture<MyComponent>
which is not supported.You either need to make an explicit initialization method that needs to be called by the user of your class like:
or you start initialization in the consturctor and allow the user of the component to wait for initialization to be done.
When
_doneFuture
was already completedawait c.initializationDone
returns immediately otherwise it waits for the future to complete first.