【问题标题】:Code after await for is not running flutter等待后的代码没有运行颤振
【发布时间】:2021-06-20 18:58:36
【问题描述】:

我正在尝试调用一个函数,该函数将通过读取流来填充列表。意思是,它将读取一个流并将值添加到一个列表中,最后,该列表将由函数返回。

问题是,当我使用 await for 读取流时,await for 之后的代码没有被执行。而且我尝试使用听,然后它不会等待完成阅读流。甚至在流被完全读取之前,监听之后的代码就已经被执行了。

按照我的代码-

Future<List<Map<String, dynamic>>> getNearestDriver(Stream<List<DocumentSnapshot>> driverWithinRangeStream, GeoPoint source) async {
    print("Get Nearest Driver Called");
    List<Map<String, dynamic>> driverAvailableList = [];
    await for (List<DocumentSnapshot> documentList in driverWithinRangeStream){
      documentList.forEach((DocumentSnapshot document) async {
        String driverIDVar = document.data['driverid'];
        GeoPoint pos = document.data['position']['geopoint'];
        var point = geo.point(latitude: pos.latitude, longitude: pos.longitude);
        double distanceVar = point.distance(lat: source.latitude, lng: source.longitude);
        int distanceInMeter = (distanceVar*1000).round();
        Map<String, dynamic> newDriverAvailable = {"driverId": driverIDVar, "distance" : distanceInMeter};
        driverAvailableList.add(newDriverAvailable);
      });
      print(driverAvailableList); /* <- I get the data here */
    }
    print(driverAvailableList); /* <- But I don't get the data here. This code is not even being executed. */
  }

请告诉我这里出了什么问题。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你想试试

    try{
        await for (List<DocumentSnapshot> documentList in driverWithinRangeStream){
            await Future.forEach(documentList, (DocumentSnapshot document) async {
               try{     
                    String driverIDVar = document.data['driverid'];
                    GeoPoint pos = document.data['position']['geopoint'];
                    var point = geo.point(latitude: pos.latitude, longitude: pos.longitude);
                    double distanceVar = point.distance(lat: source.latitude, lng: source.longitude);
                    int distanceInMeter = (distanceVar*1000).round();
                    Map<String, dynamic> newDriverAvailable = {"driverId": driverIDVar, "distance" : distanceInMeter};
                    driverAvailableList.add(newDriverAvailable);
               }catch(error){
                    throw "throw from documentList, Error:$error";}
            });
        }
     }catch(error){
         print ("catch in driverWithinRangeStream, Error:$error");}
    

    【讨论】:

    • 嗨 Sam,在这种情况下,它将从哪里获取 documentList?这段代码将只等待..对吗?
    • 是的,它应该替换documentList.forEach((DocumentSnapshot document) async {
    • 试过这个。但同样的结果。不知何故,等待没有完成,之后的代码没有读取。
    • @Alias 能否添加try()catch 以查看哪个部分是否出错。它仍然不确定哪个列表循环案例错误。可能是列表之一获取null 并抛出错误。我编辑我的答案
    猜你喜欢
    • 2020-10-25
    • 2022-11-03
    • 2019-03-30
    • 2022-06-19
    • 2020-09-01
    • 2023-04-07
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多