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