Search code examples
flutterdartgoogle-cloud-firestoreasync-awaitlisten

Code inside the firebase listen function does not execute immediately


I am trying to listen for database changes and update my datas.But the problem is that the function doesn't enter immediatly inside my for loop and my function always return me null.Have you some ideas?

Future<InfoCompagnie> getPlace(
      {String compagnie,
      String dep,
      String arr,
      String jour,
      int nbrPlace}) async {
    var infoCompagnie = InfoCompagnie().obs;
    db
        .collection('PLACE')
        .document(compagnie)
        .collection('$dep-$arr')
        .document(jour)
        .collection('Bus')
        .where('PlaceDisponible', isGreaterThanOrEqualTo: 2)
        .snapshots(includeMetadataChanges: true)
        .listen((document) {
      for (var data in document.documents) {
        if (data.exists) {
          codeBus = data.data['CodeBus'];
          infoCompagnie.update((value) {
            value.accessiblePlace = accessiblePlace;
          });
          return infoCompagnie.value;
        } else
          return null;
      }
    });
  }

Solution

  • Triggers activation depends from different kind of situtaions for example, on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available. Firestore loads data asynchronously, since it may take some time for this.

    If you want to understand better how works, check this document.

    As explained in this documentation you can write asynchronous code using futures with 'async' and 'await' keywords.

    If you need to manage synchronized operations, you can find useful examples at this document, for example:

    import 'package:synchronized/synchronized.dart';
    
    main() async {
      // Use this object to prevent concurrent access to data
      var lock = new Lock();
      ...
      await lock.synchronized(() async {
        // Only this block can run (once) until done 
        ...
      });
    }