首页 > 解决方案 > 函数返回未来

问题描述

所以我正在学习颤振,我有一个返回 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。我怎么能这样做?任何想法?

标签: flutterdart

解决方案


这应该可以解决问题,将getUserLocation()函数的返回类型设置为,Future<UserLocation?>并在没有返回任何内容的地方返回 null。


推荐阅读