来自Firestore的子收集列表问题

时间:2020-05-06 23:58:20

标签: firebase flutter dart google-cloud-firestore

您好,我是新手,但我在从Firestore获取数据到模型时遇到问题,我将说明: 我试图首先获取数据库的主要集合(称为邻居),然后在从每个邻居获得所有文档之后,我试图获取每个邻居的documentID,然后获取作为每个邻居的子集合的付款我正在尝试将数据传递给模型并为每个邻居创建该模型的列表对象。

问题是我试图返回模型列表,但是我只能向其添加邻居,付款是空列表,我要付款,我将附上代码:

  Future<List<NeighborDataModel>> getNeighborData() async {
    neighborhoodData = [];

    neighbors = await _firestore
        .collection('neighbors')
        .getDocuments()
        .then((val) => val.documents);

    for (int i = 0; i < neighbors.length; i++) {
      _firestore
          .collection('neighbors')
          .document(neighbors[i].documentID.toString())
          .collection('payments')
          .snapshots()
          .listen(createListOfPayments);

      neighborhoodData.add(NeighborDataModel.fromFirestore(neighbors[i], payments));
    }

    print(neighborhoodData.length);
    return neighborhoodData;
  }

  Future createListOfPayments(QuerySnapshot snapshot) async {
    payments = [];
    var doc = snapshot.documents;
    for (var Doc in doc) {
      payments.add(Doc);
    }
    return payments;
  }

问题:是否有办法从createListOfPayments快照函数返回付款清单,或者还有其他更好的方法来填充模型清单?

这是我的模特:

import 'package:cloud_firestore/cloud_firestore.dart';

class NeighborDataModel {
  String name;
  String lastName;
  String streetName;
  String streetNumber;
  String phone;
  String email;
  String entryCode;
  List payments;

  NeighborDataModel({
    this.name,
    this.lastName,
    this.streetName,
    this.streetNumber,
    this.phone,
    this.email,
    this.entryCode,
    this.payments,
  });

  factory NeighborDataModel.fromFirestore(
      DocumentSnapshot neighbor, List<DocumentSnapshot> payments) {

    Map neighborData = neighbor.data;

    List paymentData = [];
    for(var payment in payments){
      paymentData.add(payment.data);    }


    return NeighborDataModel(
      name: neighborData['name'],
      lastName: neighborData['last_name'],
      streetName: neighborData['street'],
      streetNumber: neighborData['house_number'],
      phone: neighborData['phone'],
      email: neighborData['email'],
      entryCode: neighborData['entry_code'],
      payments: paymentData
    );
  }
}

从以下示例获得示例: https://medium.com/@borsezf2/sub-collections-list-from-firestore-d6c6e029bed3

非常感谢!

0 个答案:

没有答案