0
votes

I have a view screen where I want to display all customers. The customers are displayed in a list view format.

In my CustomerNotifier class, I set the customer id to be the same as the currentUser id, so automatically, it should only display customers created by current logged in user.

  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();
  }    

I can successfully write to the database. However, reading all customer documents and displaying the customers created by currentUser (where document id == currentUser uid) doesn't show in my customer ListView.

I've been at this for days and can't seem to figure out why. I'd appreciate some help in what I might be doing wrong/overlooking.

Thanks.

Please note my flutter project dependency versions are as below:

  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
Is the id in the where referring to the documentID or a field in the document named id? - Akora Ing. DKB
Yes it is. I've edited the main question to include a screenshot of my firebase. it's named id. - hermie_brown
I also added my customer model class. - hermie_brown

1 Answers

2
votes

Your collection is 'customer' not 'customers' change your query to:

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