我使用 Geolocator 软件包已经有一段时间了,它运行良好,但在过去 2 天它不起作用。 我正在尝试获取最后一个已知位置,如果没有,我会尝试获取当前位置。 getLastKnownPosition() 返回 null,而 getCurrentPosition() 永远不会完成并且不返回任何内容。
PS:在android模拟器和IOS模拟器上它工作正常,但在我的android物理设备上它不起作用。
这是我的功能:
Future<Position> locateUser() async {
final result = await Geolocator.getLastKnownPosition(
forceAndroidLocationManager: true);
if (result != null) {
return result;
}
final result1 = await Geolocator.getCurrentPosition();
return result1;
}
-我已尝试卸载该应用程序并重新安装
-我尝试过关闭和打开 GPS
尝试以下几点 -
例如-
final result1 = await Geolocator.getCurrentPosition().timeout( Duration(seconds: 10), onTimeout: () { ///you can throw TimeoutException("Location request timed out."); }, );
或者你可以通过 try and catch 以及 3 次重试来重试
喜欢:-`
///try this
Future<Position> locateUser({int retries = 3}) async {
try {Future<Position> locateUser({int retries = 3}) async {
try {
/// Trying to get the last known position of the user
final result = await Geolocator.getLastKnownPosition(
forceAndroidLocationManager: true);
/// If we get a valid position
if (result != null) {
return result;
}
/// If no last known position of the user, get the current position of the user with a timeout
final result1 = await Geolocator.getCurrentPosition().timeout(
Duration(seconds: 10),
onTimeout: () {
throw TimeoutException("Location request timed out.");
},
);
return result1; // Return current position of user if successful
} catch (e) {
if (retries > 0) {
print('Location request failed, retrying... ($retries retries left)');
await Future.delayed(Duration(seconds: 2)); /// delay Wait before retrying
return locateUser(retries: retries - 1); /// Retry with reduced count
} else {
print("Failed to get location after multiple attempts.");
rethrow; /// Throw the error if out of retries
}
}
}