我们假设在Dart中初始化MyComponent需要向服务器发送HttpRequest.是否有可能同步构造一个对象并推迟"实际"初始化直到响应回来?
在下面的示例中,在打印"完成"之前不会调用_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");
}
Run Code Online (Sandbox Code Playgroud)
输出:
done
init
Run Code Online (Sandbox Code Playgroud) 我一直在调查我的Flutter应用程序的JSON解析,并且有一个关于我无法解决的工厂构造函数的问题.我试图理解使用工厂构造函数和普通构造函数的优点.例如,我看到很多JSON解析示例创建了一个带有JSON构造函数的模型类,如下所示:
class Student{
String studentId;
String studentName;
int studentScores;
Student({
this.studentId,
this.studentName,
this.studentScores
});
factory Student.fromJson(Map<String, dynamic> parsedJson){
return Student(
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
);
}
}
Run Code Online (Sandbox Code Playgroud)
我也看到过相同数量的例子,它们并没有将构造函数声明为工厂.两种类型的classname.fromJSON构造函数都是从JSON数据创建一个对象,因此将构造函数声明为工厂还是在这里使用工厂是多余的?
我有这两种方法来编写构造函数。className()和className._()
它们之间有什么区别,我什么时候应该使用哪个?
class GlobalState{
final Map<dynamic,dynamic> _data=<dynamic,dynamic>{};
static GlobalState instance = new GlobalState._();
GlobalState._();
}
//In Main Class
GlobalState _store=GlobalState.instance;
and
class GlobalState{
final Map<dynamic,dynamic> _data=<dynamic,dynamic>{};
static GlobalState instance = new GlobalState();
}
//In Main Class
GlobalState _store=GlobalState();
Run Code Online (Sandbox Code Playgroud)