firebase - 一个函数打印该值,但返回时它没有打印在另一个函数上

标签 firebase flutter dart google-cloud-firestore

我正在尝试使用 firebase 查询来获取附近的位置,并且进展顺利。这是获取附近位置的函数。

Future<List<DocumentSnapshot>> nearbyLocations() async {
    CollectionReference collectionRefer =
        FirebaseFirestore.instance.collection('locations');
    double radius = 10;
    String field = 'position';
    List<DocumentSnapshot> docList;
    GeoFirePoint center = await getCurrentLocation();
    // print(center);
    Stream<List<DocumentSnapshot>> stream = geo
        .collection(collectionRef: collectionRefer)
        .within(center: center, radius: radius, field: field, strictMode: true);
    stream.listen((List<DocumentSnapshot> documentList) {
      if (documentList.length > 0) {
        print(documentList[0].data());
        docList = documentList;
      } else {
        return {};
      }
    });
  }
我知道查询将只返回一个数据。所以,我在上面的函数中打印了第一个值。
返回 documentList 时会出现问题。
loadData() async {
    documentList =
        await GeoLocator().nearbyLocations();
  }
当我调用上面的函数时,它打印空。但是当我尝试在 nearbyLocations() 中打印时它打印数据。但不是当我调用loadData() .我将在 ListView 中使用这个返回的数据。

最佳答案

你在混await ,流和then .这可能太多了,不能同时记住。
首先专注于一种方法。我建议async/await因为这是最简单的。
您的 nearLocations 方法不会返回任何内容。您没有定义类型,它也没有返回语句。然而,您似乎希望它返回 Future<>具有指定类型。
确保提高警告并使用 pedantic包,让您的分析仪在您忘记这些事情时通知您。
当你真正完全声明你的方法时,你的警告应该告诉你你的方法没有返回。

我这里没有编译器或要包含的包,但这似乎是您真正想要的:

Future<List<DocumentSnapshot>> nearbyLocations() async {
    final collectionRefer = FirebaseFirestore.instance.collection('locations');
    final radius = 10.0;
    final field = 'position';
    final center = await getCurrentLocation();

    final stream = geo
        .collection(collectionRef: collectionRefer)
        .within(center: center, radius: radius, field: field, strictMode: true);

    return stream.first;
  }

关于firebase - 一个函数打印该值,但返回时它没有打印在另一个函数上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64568118/

相关文章:

http - Flutter : By default, Android Pie 将请求应用程序使用 HTTPS 无 HTTP 请求

android - 如何在Flutter中将项目添加到StreamController

regex - dart - 使用 RegExp 选择字符串组

ios - Firebase 从 iOS 上的用户取消链接电子邮件/密码身份验证

android - FutureBuilder 不会等待 future 完成

ios - 此假通知应转发到 firebase Swift5 iOS

database - 让 webview 在 flutter 上使用某些触发器更改数据

dart - Dart 中变量的类型声明是什么?我们推荐它的理由是什么?

javascript - Firestore云功能。https.onRequest Request.url.split ("/")不起作用

java - Android studio Firebase数据库查询选中值