I am new with flutter having issues with the future functions. I had a single await function on other screen and its returning list but when I use multiple await function in a single future function it returns an empty list and executes before many other await functions to execute. My Question is why my future functions are returning an empty list I had tried almost everything on the internet please help
Future<List<AllShefz>> getAllShefz() async {
List<AllShefz> allShefz = [];
var data = await FirebaseDatabase.instance
.reference()
.child("Resturants")
.once()
.then((DataSnapshot datasnapshot) async {
if (datasnapshot != null) {
Map<dynamic, dynamic> values = await datasnapshot.value;
values.forEach((key, value) async {
await FirebaseDatabase.instance
.reference()
.child("Resturants")
.child(key)
.child("Profile")
.once()
.then((DataSnapshot snapshot) async {
print(" I am here");
Map<dynamic, dynamic> newvals = await snapshot.value;
var position, name, gender, status;
if (await snapshot.value != null) {
position = await newvals["Position"];
name = await newvals["Name"];
gender = await newvals["Gender"];
status = await newvals["Status"];
if (position != null && status == "Approaved") {
var arr = ltlnClass().getSplit(position);
String latStr = arr[0];
String lngStr = arr[1];
String myPosition;
await new MyLocation()
.getMyLocation()
.then((value) => {myPosition = value.toString()});
var arr2 = ltlnClass().getSplit(myPosition);
String latStr2 = arr2[0];
String lngStr2 = arr2[1];
double lat2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(latStr), latStr));
double lng2 = double.parse(
ltlnClass().getLtlng(ltlnClass().getIndex(lngStr), lngStr));
double lat1 = double.parse(ltlnClass()
.getLtlng(ltlnClass().getIndex(latStr2), latStr2));
double lng1 = double.parse(ltlnClass()
.getLtlng(ltlnClass().getIndex(lngStr2), lngStr2));
double distance =
DistanceCalculator().distance(lat1, lat2, lng1, lng2);
print("Lng 1" + lng1.toString());
print("Lng 2" + lng2.toString());
print("Lat 1" + lat1.toString());
print("Lat 2" + lat2.toString());
print("Distance is " + distance.toString());
AllShefz myShef =
new AllShefz(key, position, distance, gender, name, status);
setState(() {
allShefz.add(myShef);
});
}
}
return allShefz;
});
});
} else {
print("Null value found");
}
});
return allShefz;
}
```.
You seem to be mixing
.then
andawait
calls. That is possible, but extremely error-prone for beginners (and frankly even experts if they did not have the correct dose of caffeine yet).I suggest you remove all
.then
continuations and replace them withawait
. That way you can properly debug your code and find out where you missed out on waiting for a async call. Your indentation level should shrink to something manageable and you will be able to find the mistake easily.