Dart组件:如何返回异步回调的结果?
嘿,我对Dart Futures还是陌生的,我有以下情况。
每当用户在UI中键入字母时,addressChanged()
都会调用ui_component
中的方法。此方法调用getProposals()
我的地图componenet中的方法,该方法向google maps API发出异步请求。结果到这里后,我想将它们返回到UI组件,该组件将填充UI中的propasals下拉列表。
我停留在最后一步:如何(以及最好的方法是什么)将异步回调函数的结果返回给父组件(同时保留可重用的map组件?)。
这是我尝试过的:
1)UI_Component:
// I get called if a user typed a new letter Future addressChanged(dynamic event) async {
String id = event.target.id;
String address = event.target.value;
if(id=="pickup") {
this.pickup = address;
} else if(id=="destination") {
this.destination = address;
}
// this is where I call the subcomponent and want to get the address propasals
String proposals = await googleMap.getProposals(address,id);
print(proposals);
populateProposalDropdown();
}
2)Google Map组件:
Future getProposals(String address,String id) async { await _getProposals(address,id);
}
Future _getProposals(String address,String id) async {
if(address != "") {
autocompleteService.getPlacePredictions(
new AutocompletionRequest()
..input = address
,
(predictions,status) {
List<String> result = [];
if(status == PlacesServiceStatus.OK) {
predictions.forEach(
(AutocompletePrediction prediction) =>
result.add(prediction.description)
);
}
// HERE is the problem: How do I return this result from the callback as a result of the getProposals method?
return result;
}
);
}
}
回答:
此方法不返回任何数据
Future getProposals(String address,String id) async { await _getProposals(address,id);
}
更改为
Future getProposals(String address,String id) { return _getProposals(address,id);
}
这也将工作,但在这里async和await是redunant
Future getProposals(String address,String id) async { return await _getProposals(address,id);
}
对于_getProposals你可以使用Completer
```
Future _getProposals(String address,String id) async {
if(address != “”) {
Completer completer = new Completer();
autocompleteService.getPlacePredictions( new AutocompletionRequest()
..input = address
,
(predictions,status) {
List<String> result = [];
if(status == PlacesServiceStatus.OK) {
predictions.forEach(
(AutocompletePrediction prediction) =>
result.add(prediction.description)
);
}
// HERE is the problem: How do I return this result from the callback as a result of the getProposals method?
completer.complete(result);
}
);
return completer.future;
}
return null;
}
```
以上是 Dart组件:如何返回异步回调的结果? 的全部内容, 来源链接: utcz.com/qa/427121.html