在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
question:
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?
Output:
A constructor can only return an instance of the class it is a constructor of ( You either need to make an explicit initialization method that needs to be called by the user of your class like: class MyComponent{ MyComponent(); Future init() async { print("init"); } } void main() async { var c = new MyComponent(); await c.init(); print("done"); }
or you start initialization in the consturctor and allow the user of the component to wait for initialization to be done. class MyComponent{ Future _doneFuture; MyComponent() { _doneFuture = _init(); } Future _init() async { print("init"); } Future get initializationDone => _doneFuture } void main() async { var c = new MyComponent(); await c.initializationDone; print("done"); }
When
solution2 Probably the best way to handle this is with a factory function, which calls a private constructor. In Dart, private methods start with an underscore, and "additional" constructors require a name in the form
import 'dart:async'; import 'dart:io'; class MyComponent{ /// Private constructor MyComponent._create() { print("_create() (private constructor)"); // Do most of your initialization here, that's what a constructor is for //... } /// Public factory static Future<MyComponent> create() async { print("create() (public factory)"); // Call the private constructor var component = MyComponent._create(); // Do initialization that requires async //await component._complexAsyncInit(); // Return the fully initialized object return component; } } void main() async { var c = await MyComponent.create(); print("done"); }
This way, it's impossible to accidentally create an improperly initialized object out of the class. The only available constructor is private, so the only way to create an object is with the factory, which performs proper initialization.
|
请发表评论