Build a Location Service in Flutter

Dane Mackier
Jun 12 · 3 min read

Setup

provider: ^3.0.0
location: ^2.3.5

Android

...
<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>
...
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536M
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'
}

iOS

<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>

Service Implementation

import 'package:location/location.dart';class LocationService {
UserLocation _currentLocation;
var location = Location(); Future<UserLocation> getLocation() async {
try {
var userLocation = await location.getLocation();
_currentLocation = UserLocation(
latitude: userLocation.latitude,
longitude: userLocation.longitude,
);
} on Exception catch (e) {
print('Could not get location: ${e.toString()}');
}
return _currentLocation;
}
}
class UserLocation {
final double latitude;
final double longitude;
UserLocation({this.latitude, this.longitude});
}
StreamController<UserLocation> _locationController =
StreamController<UserLocation>();
Stream<UserLocation> get locationStream => _locationController.stream; LocationService() {
// Request permission to use location
location.requestPermission().then((granted) {
if (granted) {
// If granted listen to the onLocationChanged stream and emit over our controller
location.onLocationChanged().listen((locationData) {
if (locationData != null) {
_locationController.add(UserLocation(
latitude: locationData.latitude,
longitude: locationData.longitude,
));
}
});
}
});
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return StreamProvider<UserLocation>(
builder: (context) => LocationService().locationStream,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: HomeView(),
)),
);
}
}
class HomeView extends StatelessWidget {
const HomeView({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
var userLocation = Provider.of<UserLocation>(context);
return Center(
child: Text(
'Location: Lat${userLocation?.latitude}, Long: ${userLocation?.longitude}'),
);
}
}

Flutter Community

Articles and Stories from the Flutter Community

Dane Mackier

Written by

A full stack software developer focused on building mobile products, its tools and architecture. Always reducing boiler plate code and experimenting.

Flutter Community

Articles and Stories from the Flutter Community