TimeoutException while using Geolocator in Flutter

Recently, while Implementing Geolocator Package in Flutter I got this TimeOut Exception, So Here I am Sharing the Journey, so that you can also grasp the concept and can tackle this issue.

Code:

import 'package:geolocator/geolocator.dart';Future<void> getCoordinates() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low,

);

print(position.latitude);
print(position.longitude);
} catch (e) {
print(e.toString());
}
}

Error after building the file:

TimeoutException: Timeout expired

Give me a Moment to explain what the code is doing ( for fresher in this stream)…

It is trying to access the current position of the device, basically longitude and latitude of the current device.While desiredAccuracy: is telling the function the how much accurate position we want. Like if it is okay for us that the position is here-there by few kms or not.And we are giving the parameter LocationAccuracy.low so now we are telling that we want that you can put accuracy as low and we are fine with it, so that device battery and other components are not affected.

Now, Coming Back to our Original Issue that is Timeout Exception.

So, Starting with what this issue is all about so that we will get a clear picture of why it is happening and the solution will be more clear to us.

This Exception is thrown when the time allotted for a process or operation has expired. Here it is thrown when a scheduled timeout happens while waiting for an async result. So, if we increase the time limit for this async function then this exception will be relieved.

So Let’s try that, I have added this code in the function , that is increasing the timelimit to 10 seconds:

import 'package:geolocator/geolocator.dart';Future<void> getCoordinates() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low,
timeLimit: Duration(seconds: 10),
);

print(position.latitude);
print(position.longitude);
} catch (e) {
print(e.toString());
}
}

Now Simply Run your Flutter app again, and Voilà, it’s done. Exception will be gone now.

Output:
29.3643355
59.4304381

Summary,

Timeout Exception happen in geolocator because of timelimit, so we can increase it to get the specific result.

I have mentioned all the code required that I know. If you know other ways , share in the comments for everyone!

Thanks For Reading, Follow Me For More

Annyeongヾ(•ω•`)o

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store