firebase 监听函数中的代码不会立即执行

Code inside the firebase listen function does not execute immediately

我正在尝试监听数据库更改并更新我的 datas.But 问题是该函数不会立即进入我的 for 循环并且我的函数总是 return 我null.Have你有什么想法吗?

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

触发器激活取决于不同类型的情况,例如,取决于您的连接速度和状态,可能需要几百毫秒到几秒才能获得数据。 Firestore 异步加载数据,因为这可能需要一些时间。

如果您想更好地了解工作原理,请查看此 document

如本 documentation 中所述,您可以使用带有 'async' 和 'await' 关键字的 futures 编写异步代码。

如果您需要管理同步操作,可以在此 document 找到有用的示例,例如:

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