Flutter is a framework from Google which allows you to use Dart language to write cross platform applications. This means that your apps will run on both iOS and Android devices.
If you prefer to watch a video on this topic then check out the following link:
If you are building a maps application then finding the user’s current location is an integral part of your app. 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 by simply saving the file will trigger a download of the packages. If you are using some other editor then run the following command from the terminal
flutter packages get
Now, that you have install the Geolocator package let’s go ahead and see how we can use it. We have a very basic main widget which contains a FlatButton and a Text as shown in the following code.
Next, implement the _displayCurrentLocation function.
Unfortunately, this will not work on any device or simulator since we still need to setup permissions.
For Android open gradle.properties file located in the android folder and add the following lines:
Also, make sure that the compileSDKVersion is set to 28 or above in the android/app/build.gradle file.
Finally, update the AndroidManifest.xml file located in android/app/src/main with the following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Now, let’s move to iOS :)
Open info.plist file location in ios/Runner folder and add the following entries:
<string>This app needs access to location when open.</string>
Let’s go ahead and give it a try by running the app and clicking the button. Now, when you click the button the app will request your permission to use your location. Once, you have granted the location it will find your current location and display the coordinates on the console.
In order to display the coordinates on the user interface we will need to update our widget from stateless to stateful as shown in the implementation below:
Now, when you run the app you can click on the button to display the current coordinates on the screen as shown in the screenshot below:
This article is part of my upcoming Udemy course on Flutter. Meanwhile you can support my work by checking out my other courses using the link below:
The Ultimate Hands-On Flutter & MVVM - Build Real Projects
Google Flutter framework has taken the world by storm. Flutter allows developers to write a single codebase which…
Thank you and happy coding!