【问题标题】:Flutter await not working with Firestore QuerySnapShot颤振等待不适用于 Firestore QuerySnapShot
【发布时间】:2021-10-30 09:57:53
【问题描述】:

我正在尝试获取用户联系人并在我的数据库(firestore)中搜索每个联系人的电话号码。 我成功地实现了获取联系人并为每个号码查询 firestore,但是当我想等待 get() 时,查询的结果似乎并没有等待它。

我有一个 FutureBuilder,它的未来属性是下面的函数:

Future<List<User>> doItAll() async {
    if (await FlutterContacts.requestPermission()){
      print('0');
      _phoneContacts = await FlutterContacts.getContacts(withProperties: true);
      print('0.5');
    }
    print('1');
    print('contacts ${_phoneContacts.length}');
    var fireStore = FirebaseFirestore.instance.collection('users');
    print('2');
    _phoneContacts.forEach((contact)  {
      print('3');
      contact.phones.forEach((phone) async {
        print('4');
        var query = fireStore.where('phoneNumber' , isEqualTo: phone.normalizedNumber);
        print('4.5');
        query.get().then((value) => print('this is getting out of hand'));
        var res = await query.get();
        print('5');
        res.docs.forEach((querySnapShot)  {
          print('6');
          _currentUserContacts.add(User(phoneNumber: querySnapShot.data()['phoneNumber'], userId: querySnapShot.id,displayName: contact.displayName));
        });
      });
    });
    print('this is returning');
    return List.from(_currentUserContacts);
  }

这是调试控制台的输出

I/flutter (10089): 0
I/flutter (10089): 0.5
I/flutter (10089): 1
I/flutter (10089): contacts 1
I/flutter (10089): 2
I/flutter (10089): 3
I/flutter (10089): 4
I/flutter (10089): 4.5
I/flutter (10089): this is returning
W/DynamiteModule(10089): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(10089): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(10089): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/flutter (10089): this is getting out of hand
I/flutter (10089): 5
I/flutter (10089): 6

由于某种原因,断点调试在之后没有继续

await FlutterContacts.getContacts(withProperties: true);

非常感谢任何帮助, ps:我认为这种对每个循环都有所有这些的方法效率不高。如果您有更好的想法,请与我分享。

【问题讨论】:

标签: flutter google-cloud-firestore dart-async flutter-future


【解决方案1】:

为了等待,你不应该使用 for each,把它改成

for(final u in _phoneContacts){
 // your logic
}

for each 函数执行,但您的主要函数从不等待它完成。

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2021-10-06
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2020-05-06
    • 2020-01-04
    • 2020-09-01
    • 2023-04-07
    相关资源
    最近更新 更多