I am using flutter and I have a simple method that reads each user present in my database and adds them to a list, once finished reading the users, the method must return the list containing all the data read, my problem is that my function does not wait that the Listener has finished reading and then returns my list (myList) even before the Listener has finished reading. How can I wait for the return myList until the Listener has read all the elements?
Here's the code:
Future<List<String>> getUsers () async { List<String> myList = []; final mRef = FirebaseDatabase.instance.ref().child("Users"); mRef.onValue.listen((event) async { for (final child in event.snapshot.children) { myList.add( child.value.toString() ); //ADDS THE VALUE TO THE LIST } }); //RETURN THE LIST return myList; } I tried to put an await in front of my Listener but nothing worked.