Emm*_*el 0 flutter flutter-dependencies
我正在使用位置插件来获取设备的当前位置。但是,在某些设备上, 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;
}
Run Code Online (Sandbox Code Playgroud)
为您的未来使用超时来处理这种情况:Flutter - Future Timeout
像这样使用你的未来:
var result = await getCurrentLocation().timeout(const Duration(seconds: 5, onTimeout: () => null));
Run Code Online (Sandbox Code Playgroud)
现在,您的 future 运行 5 秒,如果操作尚未完成,则 future 以 null 完成(因为 onTimeout 返回 null。您可以根据需要使用不同的值[请参阅上面的链接])。
现在检查结果。如果为空,则操作未在指定的时间限制内完成,否则,如果它设法在指定的持续时间内完成,您将照常获得您的位置值。
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |