在 Flutter 中,如何在嵌套异步函数中完成 Future 后 return 一个对象?
In Flutter how can I return an object after completion of Future in nested async functions?
我有一个函数可以调用 return 一个 Future 的各种其他函数,并且在一个 Future 完成后另一个 return 调用 future 的方法,最后我需要 return 一个值作为变量,但问题是函数 returns NULL 而不是值。
_getLocationPermission()等待并获得所需的权限,我必须等到获得权限后才能获得权限我必须调用_getCurrentLocation() 这将 return 一个 Future < LocationData > 我必须将这个对象的数据传递给 getWeatherDetails() 它最终将 return 一个 Future< String > 我不知道如何在 return 语句中 return 这个字符串。
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;
}
谢谢!
您似乎 return 从获取天气详细信息函数而不是 Future 解析异步响应,正如您的函数 return 类型所示。
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;
}
我有一个函数可以调用 return 一个 Future 的各种其他函数,并且在一个 Future 完成后另一个 return 调用 future 的方法,最后我需要 return 一个值作为变量,但问题是函数 returns NULL 而不是值。
_getLocationPermission()等待并获得所需的权限,我必须等到获得权限后才能获得权限我必须调用_getCurrentLocation() 这将 return 一个 Future < LocationData > 我必须将这个对象的数据传递给 getWeatherDetails() 它最终将 return 一个 Future< String > 我不知道如何在 return 语句中 return 这个字符串。
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;
}
谢谢!
您似乎 return 从获取天气详细信息函数而不是 Future 解析异步响应,正如您的函数 return 类型所示。
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;
}