使用Flutter在Firebase中使用Stream <QuerySnapshot>检索数据

时间:2019-11-16 14:43:56

标签: firebase flutter dart google-cloud-firestore

也许这是一个新手问题,但是我正在学习动荡,异步,等待,未来之类的东西还不适合我。无论如何,我想做的是从“ field.documents [index] [“ name”]”中获取值并建立一个列表。这是我的代码:

String productName;

Stream<QuerySnapshot> productRef = Firestore.instance
    .collection("stores")
    .document(name)
    .collection("products")
    .snapshots();
productRef.forEach((field) {
  field.documents.asMap().forEach((index, data) {
    productName = field.documents[index]["name"];
    //IF I PRINT HERE, IT SHOWS THE PRODUCTS. 
  });
});
BUT IF I PRINT HERE, I GOT A NULL VALUE

我想让productName在forEach之外。当我打印时,它首先打印null。我也将发布整个功能:

List mapToList({DocumentSnapshot doc, List<DocumentSnapshot> docList}) {
    if (docList != null) {
      List<Store> storeList = [];
      docList.forEach((document) {
        String name = document.data[StringConstant.nameField];
        num score = document.data[StringConstant.scoreField];
        String delivery = document.data[StringConstant.deliveryField];
        String photo = document.data[StringConstant.photoField];
        String description = document.data[StringConstant.descriptionField];
        String open = document.data[StringConstant.openField];
        String close = document.data[StringConstant.closeField];
        GeoPoint geoPoint = document.data[StringConstant.positionField]
            [StringConstant.geopointField];

        bool isOpen = document.data[StringConstant.isOpenField];
        final currentHour = DateTime.now();
        final openHour = DateTime.parse(open).hour;
        final closeHour = DateTime.parse(close).hour;
        int openMin = DateTime.parse(open).minute;
        int closeMin = DateTime.parse(close).minute;
        if (openHour <= currentHour.hour && currentHour.hour <= closeHour) {
          isOpen = true;
          if ((currentHour.hour == openHour && currentHour.minute < openMin) ||
              (currentHour.hour == closeHour &&
                  currentHour.minute > closeMin)) {
            isOpen = false;
          }
        } else {
          isOpen = false;
        }
        final double meter = distance(
          LatLng(latitude, longitude),
          LatLng(geoPoint.latitude, geoPoint.longitude),
        );

        String productName;

        Stream<QuerySnapshot> productRef = Firestore.instance
            .collection("stores")
            .document(name)
            .collection("products")
            .snapshots();
        productRef.forEach((field) {
          field.documents.asMap().forEach((index, data) {
            productName = field.documents[index]["name"];
          });
        });

        if (meter <= range && isOpen == true) {
          Store otherStore = Store(name, photo, score.toDouble(), delivery,
              meter, description, productName, 10.0, "");
          storeList.add(otherStore);
        }
      });
      return storeList;
    } else {
      return null;
    }
  }

有人可以帮我吗?我了解异步编程,但是我正在学习。谢谢!!!

1 个答案:

答案 0 :(得分:0)

我要在这里做

List<String> productName= [];

Stream<QuerySnapshot> productRef = Firestore.instance
    .collection("stores")
    .document(name)
    .collection("products")
    .snapshots();
productRef.forEach((field) {
  field.documents.asMap().forEach((index, data) {
    productName.add(field.documents[index]["name"]);
  });
});

您可以在查询外部初始化一个数组,以便每次“ .forEach”迭代时都可以向其中添加一个字符串。您可以执行的操作,而不是手动输入函数中的每个数据,可以创建一个数据模型以将数据库中的数据存储到本地变量中,该本地变量比手动执行field.documents ['dataField']更灵活。这是一些有用的链接:https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51