Build a Location Service in Flutter

Last updated 31 days ago by Dane Mackier

flutter

Getting your location in Flutter is an easy task. This tutorial will show you how to wrap the location package into a service that’s easy to consume in your application.

Create a new Flutter project and follow along.

Setup

Provider is my default dependency provider/state management solution so we’ll use that as well. We’ll add both packages to the pubspec.

provider: ^3.0.0 location: ^2.3.5

Android

Add the location permission into the AndroidManifest.xml manifest outside of the application tag.

... <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application android:name="io.flutter.app.FlutterApplication" android:label="The Guardian" android:icon="@mipmap/ic_launcher"> ... </application> ...

Update your gradle.properties file to this

android.enableJetifier=true android.useAndroidX=true org.gradle.jvmargs=-Xmx1536M

Update your build.gradle file dependencies to this

dependencies { classpath 'com.android.tools.build:gradle:3.3.0' classpath 'com.google.gms:google-services:4.2.0' }

And make sure your compileSdkVersion is 28.

iOS

Add the Location Permissions to your info plist with the appropriate Messages.

<key>NSLocationWhenInUseUsageDescription</key> <string>This app requires access to your location for FilledStacks tutorial.</string> <key>NSLocationAlwaysUsageDescription</key> <string>This app requires access to your location for FilledStacks tutorial.</string>

That’s all the setup done. If you’re running into AndroidX problems make sure to migrate or use an older version of this package if you don’t want to migrate.

Service Implementation

If there’s one thing I can recommend is to read up on the Single Responsibility Principle. Based on this I’ve made it a habit to architect my apps using single-purpose services that I inject/locate where required. Let’s create our LocationService. This service will:

  1. Provider a stream of continuous updates we can depend on
  2. Provider a function to do a once off request for the current location
Read full Article