0

我正在尝试获取用户联系人并在我的数据库(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:我认为这种针对每个循环的所有这些方法效率不高。如果您有更好的想法,请与我分享。

4

1 回答 1

1

为了等待,您不应该使用 for each,将其更改为

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

for each 函数执行,但您的主要函数永远不会等待完成。

于 2021-08-31T20:59:17.180 回答