假设 Dart 中 MyComponent 的初始化需要向服务器发送 HttpRequest。是否可以同步构造一个对象并推迟“真正的”初始化直到响应返回?
在下面的示例中,直到打印“done”后才会调用 _init() 函数。可以解决这个问题吗?
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");
}
输出:
done
init
最佳答案
处理这个问题的最佳方法可能是使用工厂函数,它调用私有(private)构造函数。
在 Dart 中,私有(private)方法以下划线开头,并且“附加”构造函数需要采用 ClassName.constructorName
形式的名称,因为 Dart 不支持函数重载。这意味着私有(private)构造函数需要一个以下划线开头的名称(在下面的示例中为MyComponent._create
)。
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");
}
这样,就不可能意外地从类中创建未正确初始化的对象。唯一可用的构造函数是私有(private)的,因此创建对象的唯一方法是使用工厂,它执行正确的初始化。
关于asynchronous - 从 Dart 中的构造函数调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933801/