HttpRequest.getString(...)
返回Future
(在JS/TS土地Promise
),否则您将无法调用.then(...)
的结果。
您可以使用async
/await
class Component {
var property;
Component() async {
await HttpRequest.getString("/path/to/something")
.then((resp) {
property = JSON.decode(resp);
});
doSomethingAfterRequestReturned();
}
}
没了 - 你不能在构造函数中使用async
/await
。
替代品是静态方法或对象创建后的额外调用。无论如何,在构造函数中做广泛的工作是不好的习惯。
class Component {
Future<Component> createNewInstance() async {
var c = new Component();
await HttpRequest.getString("/path/to/something")
.then((resp) {
c.property = JSON.decode(resp);
});
return c;
}
var property;
}
和一个额外的呼叫
class Component {
getData() {
return HttpRequest.getString("/path/to/something")
.then((resp) {
property = JSON.decode(resp);
});
}
var property;
}
使用它像
Component.createNewInstance().then((c) => print(c.property));
,并使用它像
var c = new Component()
c.getData().then((_) => print(c.property));