Dart组件:如何return异步回调的结果?

Dart Component: How to return result of asynchronous callback?

嘿,我是 Dart Futures 的新手,我遇到了以下情况。

每当用户在 UI 中键入一个字母时,我的 ui_component 中的 addressChanged() 方法就会被调用。此方法调用我的地图组件中的方法 getProposals(),该方法对 google 地图 API 执行异步请求。一旦结果在这里,我想将它们 return 到 UI 组件,该组件将填充 UI.

中的提案下拉列表

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

这是我试过的:

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 地图组件:

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

此方法不return任何数据

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