【问题标题】:Function returns Future<dynamic>函数返回 Future<dynamic>
【发布时间】:2021-10-29 04:27:27
【问题描述】:

所以我正在学习颤振,我有一个返回 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

无论如何,关键是每当我从其他地方调用此函数时,我都想访问此方法返回的 UserLocation 对象,但它总是说此函数返回 Future。我怎么能这样做?有什么想法吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 2022-12-09
      • 2019-06-28
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多