flutter - 函数返回未来
问题描述
所以我正在学习颤振,我有一个返回 UserLocation 对象的函数 -
getUserLocation() async {
bool _serviceEnabled;
loc.PermissionStatus _permissionGranted;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == loc.PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != loc.PermissionStatus.granted) {
return;
}
}
try {
_currentPosition = await location.getLocation();
} catch (e) {
print(e);
}
List<geo.Placemark> placemarks = await geo.placemarkFromCoordinates(
_currentPosition.latitude ?? 0, _currentPosition.longitude ?? 0);
var countryNameList = placemarks[0].country?.split(' ');
if (countryNameList!.isNotEmpty && countryNameList.length >= 2) {
for (var eachLetter in countryNameList) {
abbr += eachLetter[0];
}
} else {
abbr = countryNameList.toString().substring(0, 2).toUpperCase();
}
return UserLocation(
city: placemarks[0].locality ?? 'Chennai',
country: abbr,
latitude: _currentPosition.latitude,
longitude: _currentPosition.longitude);
}
现在,当我调用这个函数时,它说它返回 Future<dynamic)..Future 因为它是一个异步函数和动态的,因为如果 location.ServiceEnabled 或 location.hasPermission 失败,它不会真正返回任何内容。
无论如何,关键是每当我从其他地方调用此函数时,我都想访问此方法返回的 UserLocation 对象,但它总是说此函数返回 Future。我怎么能这样做?任何想法?
解决方案
这应该可以解决问题,将getUserLocation()
函数的返回类型设置为,Future<UserLocation?>
并在没有返回任何内容的地方返回 null。
推荐阅读
- docker - 对 nginx 后面的 docker 私有注册表的请求由 HTTPS 虚拟主机处理
- cakephp - Cakephp 2多维cookie数组不起作用
- regex - URL 中带有 slug 的 Django RedirectView
- c# - 将派生类作为参数传递时,调试器是否应该抛出一些警告?
- php - 如何在php中获取星期之间的日期
- ubuntu - 鳄梨酱 Guacd 安装 Ubunutu
- swift - swift: 十六进制字符串加倍
- java - Selenium Headless Chrome 位置不同
- c# - 从列表中删除一系列项目而不循环
- php - 使用 Laravel 的 PHP 应用程序服务器