Mateen Kiani
Mateen Kiani

Reputation: 3273

In Flutter how can I return an object after completion of Future in nested async functions?

I have a function which calls various other functions that return a Future and after the completion of one Future another method that return a future is called and in the end i need to return a value as a variable but the problem is that function returns NULL instead of the value.

_getLocationPermission() waits and gets the required permission, i have to wait until I get the permission after getting permission I have to call _getCurrentLocation() which will return a Future < LocationData > and i have to pass this object's data to getWeatherDetails() and it will eventually return a Future< String > and i don't know how can i return this string in the return statement.

Future<String> getData() async {
String longitude, latitude, weatherDetails;
_getLocationPermission().then((permissionStatus) {
  _getCurrentLocation().then((location) async {
    longitude = location.longitude.toString();
    latitude = location.latitude.toString();
    weatherDetails = await getWeatherDetails(longitude, latitude);
    print(longitude);
  });
});

return weatherDetails;

}

Thanks!

Upvotes: 0

Views: 6390

Answers (1)

Isaac Obella
Isaac Obella

Reputation: 2643

You seem to be returning a resolve aync response from the getWeatherDetails function not a Future as your function return type shows.

Future<String> getData() async { 
    var weather;
     _getLocationPermission().then((_){
    var location  = await _getCurrentLocation();

    weather = getWeatherDetails(location.longitude.toString(), location.latitude.toString());
    })
.catchError((error){
// Handle if location permission fails
});

   return weather;
}

Upvotes: 2

Related Questions