Reputation: 101
I've been using the Geolocator package for a while and it works good, but for the last 2 days it's not working. Am trying to get last known position, and if there is none i try to get the current posiotion. getLastKnownPosition() returns null, and the getCurrentPosition() never finishes and doesn't return anything.
PS: On android emulator and IOS simulator it works fine, but in my android physical device it doesn't work.
Here is my function:
Future<Position> locateUser() async {
final result = await Geolocator.getLastKnownPosition(
forceAndroidLocationManager: true);
if (result != null) {
return result;
}
final result1 = await Geolocator.getCurrentPosition();
return result1;
}
-I have tried uninstalling the app and re-install
-I have tried turning off and on GPS
Upvotes: 1
Views: 162
Reputation: 299
Make sure your app has permission
to access your location
check here
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
LocationPermission permission = await Geolocator.checkPermission();
if (!serviceEnabled) {
// do what you want
}
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
toast('Please location permission');
logger.w("get User LocationPosition()");
await Geolocator.openAppSettings();
throw '${language.lblLocationPermissionDenied}';
}
}
Upvotes: 0
Reputation: 41
Try these following points -
for e.g. - final result1 = await Geolocator.getCurrentPosition().timeout( Duration(seconds: 10), onTimeout: () { ///you can throw TimeoutException("Location request timed out."); }, );
or you can retry by try and catch and also by 3 retries
like :- `
///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
}
}
}
Upvotes: 0