【问题标题】:How do I handle a future not returning?我如何处理未来不回来?
【发布时间】:2021-04-23 10:05:45
【问题描述】:

我正在使用位置插件来获取设备的当前位置。但是,在某些设备上,await getLocation() 永远不会返回(调试控制台中也没有错误)。我该如何处理这样的问题?

这是我的 getCurrentLocation() 代码

import 'package:geolocator/geolocator.dart';
import 'location.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> getCurrentLocation() async {
  bool serviceEnabled;
  LocationPermission permission;
  Position position;
  await reqLocation(); // requests turn on location
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.deniedForever) {
    return Future.error(
        'Location permissions are permantly denied, we cannot request permissions.');
  }

  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission != LocationPermission.whileInUse &&
        permission != LocationPermission.always) {
      return Future.error(
          'Location permissions are denied (actual value: $permission).');
    }
  }
  print('LOGIC');
  position = await Geolocator.getCurrentPosition();
  if (position == null) {
    print('null');
  } else {
    print('LOCATION');
    print(position);
  }
  return position;
}

【问题讨论】:

标签: flutter flutter-dependencies


【解决方案1】:

为您的未来使用超时来处理这种情况:Flutter - Future Timeout

这样使用你的未来:

var result = await getCurrentLocation().timeout(const Duration(seconds: 5, onTimeout: () => null));

现在,你的 future 运行 5 秒,如果操作尚未完成,future 以 null 结束(因为 onTimeout 返回 null。你可以根据需要使用不同的值 [参考上面的链接] )。

现在检查结果。如果为 null,则操作未在指定的时间限制内完成,否则如果成功在指定的持续时间内完成,您将像往常一样在结果中获得您的位置值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2021-03-27
    • 2013-11-06
    • 2020-12-28
    相关资源
    最近更新 更多