[Flutter] Finding User’s Location

Tram Ho

Flutter is a framework from Google that allows you to use the Dart language to write cross-platform applications. This means your application will run on both iOS and Android devices.

If you are building a mapping application, finding the user’s current location is an integral part of your application. Fortunately, Flutter makes it super simple using the Geolocator package. The first step is to install the Geolocator package by adding it to the pubspec.yaml file as shown below:

If you are using VS Code then just save the file to download the package. If you are using some other editor, then run the following command from the command line terminal:

Now that you’ve installed the Geolocator package, let’s find out how to use it. For example, I will have a screen with very basic widgets, containing FlatButton and Text like below:

Next, implement the _displayCurrent functionLocation.

Unfortunately, it will not work on any device or simulator because we will need to set permissions . For Android, open the gradle.properIES file in the Android directory and add the following lines:

Also, make sure that compileSDKVersion is set to 28 or higher in the android / app / build.gradle file.

Finally, update the AndroidManifest.xml file found in android / app / src / main with the following permissions :

Next, config for iOS. Open the location of the info.plist file in the ios / Runner folder and add the following:

That’s it, now we will try it by running the application and clicking on the button. When you click the button, the application will ask you for permission to use your location. Once you have granted the location, it will find your current location and display the coordinates on the console. To display the coordinates on the user interface, we will need to update the widget from stateless to stateful . How to implement the following:

And now, when you run the application, you can click the “Find Current Location” button to display the current coordinates on the screen as shown in the screenshot below:

Thank you for reading the article. Thanks u

References:

Share the news now

Source : Viblo