Firestore call returning before the end of the run, on flutter

Asked

Viewed 47 times

0

I have a function to search the data in the firestore. I call the function that is in a controller class helper.getTodosAgendures(); Works well.

Below a snippet of my firestore search function.

//Classe Controladora
CollectionReference cr = await FirebaseFirestore.instance.collection('parceiros').doc(identificador).collection("agendamento");
      print(cr.toString());
      await cr.snapshots().listen((snapshot) async {
        print("ENTROU NO ASYNC");
        for(int i=0;i<snapshot.size;i++){

          if (snapshot.docs[i].exists) { 
            //print("AG" +snapshot.docs[i].data()["agendamento"].toString());

            listAgendamentos.add(Agendamento.fromMap(snapshot.docs[i].data()["agendamento"]));
            print(listAgendamentos.elementAt(i));
            //Map data = await snapshot.docs[i].data()["clientes"];

          }

        }

        print("lista agendamentos tamanho no retorno ${listAgendamentos.length} ${DateTime.now().toString()}");
        print("RETORNOU A LISTA NUVEM");


      });

      return  listAgendamentos;

Below a snippet my function that consumes the return of the firestore. PS: I used Delayed only for testing, it will be removed.

//Classe Consumidora
await helper.getTodosAgendamentos().then((listaAgendamentos)=> agendamentoObject=listaAgendamentos);

        //print(agendamentoObject.toString());

    new Future.delayed(new Duration(milliseconds: 100), (){
      print("agendamentos OBJECTO tamanho "+agendamentoObject.length.toString());

      marcacoes.add(DecorationItem(
          decorationAlignment: FractionalOffset.bottomRight,
          date: DateTime.now(),
          decoration: Icon(
            Icons.today,
            color: Colors.blue,
          )));

      for(i=0;i<agendamentoObject.length;i++){
        print("ID "+agendamentoObject[i].idAgendamento.toString());

        int horas = parseDuration("${agendamentoObject[i].duracaoAgendamento}").inHours;
        int minutos = parseDuration("${agendamentoObject[i].duracaoAgendamento}").inMinutes-(60*horas);
        DateTime dataAgendada = DateTime.parse("${agendamentoObject[i].dataAgendamento}");
        DateTime fimAgendamento = dataAgendada.add( Duration(hours: horas,minutes:minutos ));
        String nomeDoCliente = "${agendamentoObject[i].clienteAgendamento}";
        String procedimento = "${agendamentoObject[i].procedimentoAgendamento}";
        String observacao = "${agendamentoObject[i].observacaoAgendamento}";
        int idAgend = agendamentoObject[i].idAgendamento;
        String whatsapp = "${agendamentoObject[i].whatsappAgendamento}";


        marcacoes.add(DecorationItem(
            date: dataAgendada,
            decoration: Text(
              'Agendamento',
              style: TextStyle(
                color: Colors.brown,
                fontWeight: FontWeight.w600,
              ),
            )
        ));


        events.add(FlutterWeekViewEvent(
          title: nomeDoCliente,
          start: dataAgendada,
          end: fimAgendamento,
          description: procedimento,
          onTap: (){
            editaEvento(context,idAgend,nomeDoCliente,procedimento,dataAgendada,fimAgendamento,observacao,whatsapp);
          },
        ));
      }
    });

With the delayed I confirmed what I already knew, the later code ta being executed before the return of the function.

What I would like to do through the asynchronous function and the use of the await was that the code later awaited the execution and return of the getTodosAgendures list() and only after that continued the execution.
I apologize, in the post the indentation was half crooked, but I believe it is readable.

Summing up my problem
When you arrive at this stretch await cr.snapshots().listen((snapshot) async {...}
The consumer class continues execution without the controller having finished and returned the list, so it does not occur to fill the widgets

Why does this happen? Any suggestions on how to resolve?

  • People of negativity, would you please explain what the problem is with my question? I explained what I did and I showed what I partially solved, I made a long explanation and a summary of the doubt, I would appreciate it if you would comment on what is the problem for me not to repeat, instead of just pressing a negative button. :)

  • 1

    I advise you to better understand how the synchronous and asynchronous functions in Flutter work... You don’t know how to handle it, using the await you do not need to use the then and vice versa... You are trying to wait a listen, and the same is to be "listening", so it is not to use the await... Give me a read on this one reply to understand a little more.

  • 1

    Matheus, thank you so much for your reply. You pointed out an error that I hadn’t noticed. In fact I had already read about Async Await and then/Whencomplete, the issue of Istener is that because of organization I wanted to keep the code out of the widget consuming class, but to uncomplicate my life, I created the function inside the class by passing the snapshot in the widgets construction.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.