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));