Flutter await not working with Firestore QuerySnapShot


I am trying to get users contacts and search my database(firestore) for each contact’s phone number .
I successfully achieve getting contacts and querying firestore for each number but i when I want to await to get() the results of the query flutter doesn’t seem to wait for it.

I have a FutureBuilder which it’s future property is the function below:

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

this is debug console’s output

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

and for some reason breakpoint debugging doesnt continue after

await FlutterContacts.getContacts(withProperties: true);

any help is much appreciated,
ps: I think this kind of approach with all these for each loops is not efficient . please if you any better idea share it with me .


In order to await, you shouldn’t use for each,change it to

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

The for each function execute but your main functions never wait for that completes.

Answered By – Nicolás López

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *