Article Image

User location in Flutter

8th October 2018

Hi everybody!

In this post, we'll see how to get user location in Flutter.

In pubspec.yaml file adds the following dependency:

2geolocator: '^5.1.4'

The main class is Geolocator, so we have to talk with that class.

We suppose we need to get the current user location. Well, we need to call getCurrentPosition method from Geolocator class.

By default, the desiredAccuracy param is, which is also fine. getCurrentPosition method returns a Future which is very important otherwise it freezes UI in Flutter. This is an excellent practice to keep a fluent flow.

In order to make an operation over the result, we can add .then() method from Future class and we can make whatever function. e.g. we can print and store location in a LocationRepository which is just a reference in memory.

Finally, we have the following code:

Having this method, we can make whatever we want. e.g:

  • We can call it, add another .then() in View layer and call setState() to change a field.
  • If we have a FutureBuilder we can use locateUser() in future property.
  • We can call it and make a query in a database.

Etc, etc.

That's all folks!


More Than Code LLC

Address: 8 The Green STE B, Dover, DE 19901

Phone: +1 856-786-4408


© Copyright 2022 All right reserved to More Than Code LLC