首页 > 解决方案 > 一个函数打印该值,但返回时它没有打印在另一个函数上

问题描述

我正在尝试使用 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()。我将在列表视图中使用这个返回的数据。

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


你正在混合await,流和then。这可能太多了,不能同时记住。

首先专注于一种方法。我建议async/await因为这是最简单的。

您的 nearLocations 方法不会返回任何内容。您没有定义类型,它也没有返回语句。但是,您似乎希望它返回Future<>具有指定类型的 a。

确保您提高警告并使用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;
  }

推荐阅读