嘿,我对Dart Futures很新,并且遇到了以下情况。
每当用户在UI中键入字母时,我的ui_component中的addressChanged()方法被调用。该方法调用maps组件中的getProposals()方法,该方法对google maps API进行异步请求。一旦结果出现,我希望将它们返回给UI组件,后者将填充UI中的建议下拉列表。
我卡在了最后一步:如何(以及最好的方法是什么)将异步回调函数的结果返回给父组件(同时保持可重用的地图组件)。
这是我尝试过的:
1)UI_Component:
每当用户在UI中键入字母时,我的ui_component中的addressChanged()方法被调用。该方法调用maps组件中的getProposals()方法,该方法对google maps API进行异步请求。一旦结果出现,我希望将它们返回给UI组件,后者将填充UI中的建议下拉列表。
我卡在了最后一步:如何(以及最好的方法是什么)将异步回调函数的结果返回给父组件(同时保持可重用的地图组件)。
这是我尝试过的:
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
的麻烦。 - Argenti Apparatus