【发布时间】:2017-07-02 20:47:42
【问题描述】:
嘿,我是 Dart Futures 的新手,我遇到以下情况。
每当用户在 UI 中键入一个字母时,我的 ui_component 中的 addressChanged() 方法就会被调用。此方法在我的地图组件中调用 getProposals() 方法,该方法向谷歌地图 API 发出异步请求。一旦结果在这里,我想将它们返回到 UI 组件,该组件将填充 UI 中的 propasals 下拉列表。
我坚持最后一步:如何(以及最好的方法)将异步回调函数的结果返回给父组件(同时保留可重用的地图组件?)。
这是我尝试过的:
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) 谷歌地图组件:
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;
}
);
}
}
【问题讨论】:
-
AutoCompleteService是您的代码吗?可以将其重写为返回Future本身而不是调用回调,这样您在调用它时就不必使用Completer。 -
不,不幸的是它不是:pub.dartlang.org/packages/google_maps。他们真的应该像这样实现库 ;-)
标签: asynchronous dart dart-async angular2-dart