问题描述
嘿,我是Dart Futures的新手,我有以下情况.
每当用户在UI中键入字母时,我的ui_component中的addressChanged()方法都会被调用.此方法在我的地图组合中调用方法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)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; }