gpt4 book ai didi

asynchronous - Dart 组件 : How to return result of asynchronous callback?

转载 作者:行者123 更新时间:2023-12-03 02:44:45 28 4
gpt4 key购买 nike

嘿,我对 Dart Futures 很陌生,我有以下情况。

每当用户在 UI 中键入一个字母时,addressChanged()我的 ui_component 中的方法被调用。该方法调用方法getProposals()在我的 map 组件中,它向谷歌地图 API 发出异步请求。一旦结果在这里,我想将它们返回到 UI 组件,该组件将填充 UI 中的 propasals 下拉列表。

我坚持最后一步:如何(以及最好的方法)将异步回调函数的结果返回给父组件(同时保留可重用的 map 组件?)。

这是我尝试过的:

1) UI_组件:

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

最佳答案

此方法不返回任何数据

  Future getProposals(String address,String id) async {
await _getProposals(address,id);
}

将其更改为
  Future getProposals(String address,String id) {
return _getProposals(address,id);
}

这也可以,但在这里 asyncawait是多余的
  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;
}

关于asynchronous - Dart 组件 : How to return result of asynchronous callback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42228246/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com