Search code examples
fluttergoogle-cloud-firestorestream-builder

How to recover a specific data in the firestore?


I have this structure in the database:

enter image description here

I have a function that return the current user logged

 FirebaseAuth auth = FirebaseAuth.instance;
 auth.currentUser.uid;

And i want to retrieve "requisicoes" when "idUser" == auth.currentUser.uid;

Basically, the user retrieves the requests created by himself.

That's my StreamBuilder

final _controller = StreamController<QuerySnapshot>.broadcast();
FirebaseFirestore db = FirebaseFirestore.instance;

StreamBuilder<QuerySnapshot> addListenersRequests() {
final stream = db
    .collection("requisicoes")
    .where("usuario.idUser", isEqualTo: idUsuarioLogado)
    .snapshots();


stream.listen((dados) {
  _controller.add(dados);
});
return null;

}

Note: idUsuarioLogado is returning correctly currentUser

The problem is that I am getting everything in the "requisicoes" collection, when I create a new user, other users' requests appear on the screen

is there a logic problem in StreamBuilder?


Solution

  • I found the answer here Firestore is ignoring the where clause in the query in flutter

    My example is the same as the link above, I have two functions, one addListenersRequests() and the other getCurrentUser(), these two functions I was calling in the initState method, the problem is that getCurrentUser is async, so addListenersRequests () was being executed first, before the value of the variable idUsuarioLogado is filled.

    So I merged the two functions into one, so that getCurrentUser can be executed first

    Final code:

    Future<StreamBuilder<QuerySnapshot>> addListenersRequests() async{
    
    await getDataUser();
    
    final stream = db
        .collection("requisicoes")
        .where("usuario.idUser", isEqualTo: idUsuarioLogado)
        .snapshots();
    
    stream.listen((dados) {
      _controller.add(dados);
    });
    return null;
    

    }

    Now it is working correctly.

    The strange thing about this story is that the firebase executes the clause and retrieves everything in the collection even when the referenced variable is null