如何在Flutter Firebase中查询多个文档,其中id为isEqualTo currentUser uid? -扑火基地

时间:2020-10-05 10:00:03

标签: firebase flutter google-cloud-firestore flutter-dependencies provider

我有一个查看屏幕,我想在其中显示所有客户。客户以列表视图格式显示。

在我的CustomerNotifier类中,我将客户ID设置为与currentUser ID相同,因此自动地,它应该仅显示由当前登录用户创建的客户。

  getCustomers(CustomerNotifier customerNotifier) async {
    String userId = (await FirebaseAuth.instance.currentUser()).uid;

    print('Current logged in user uid is: $userId');

    QuerySnapshot snapshot = await Firestore.instance
        .collection('customers')
        .where("id", isEqualTo: userId)
        .orderBy('created_at', descending: true)
        .getDocuments();

    List<Customer> _customerList = [];

    snapshot.documents.forEach((document) {
      Customer customer = Customer.fromMap(document.data);
      _customerList.add(customer);
    });

    customerNotifier.customerList = _customerList;
  }    

  Future createOrUpdateCustomer(Customer customer, bool isUpdating) async {
    CollectionReference customerRef =
        await Firestore.instance.collection('customer');
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    String userId = user.uid;
    print('Current logged in user uid is: $userId');

    if (isUpdating) {
      customer.updatedAt = Timestamp.now();
      await customerRef.document(userId).updateData(customer.toMap());
      print('updated customer with id: ${customer.id}');
    } else {
      customer.createdAt = Timestamp.now();

      DocumentReference documentReference = await customerRef.document(userId);
      // add(customer.toMap());

      customer.id = documentReference.documentID;

      print('created customer successfully with id: ${customer.id}');

      await documentReference.setData(customer.toMap(), merge: true);
      addCustomer(customer);
    }
    notifyListeners();
  }    

我可以成功写入数据库。但是,读取所有客户文档并显示由currentUser创建的客户(文档ID == currentUser uid)显示在我的客户ListView中。

我已经待了好几天了,似乎无法弄清楚为什么。对于可能会做错/忽略的事情,我将不胜感激。

谢谢。

请注意,我的Flutter项目依赖项版本如下:

  firebase_core: ^0.4.5
  firebase_auth: ^0.16.1
  cloud_firestore: ^0.13.7
  provider: ^4.3.1
  firebase_storage: ^3.1.0

1 个答案:

答案 0 :(得分:1)

您的收藏集是“客户”而不是“客户”,将查询更改为:

QuerySnapshot snapshot = await Firestore.instance
    .collection('customer')
    .where("id", isEqualTo: userId)
    .orderBy('created_at', descending: true)
    .getDocuments();