Simple Location Tracking App in Flutter
Simple Location Tracking App in Flutter:
Hello everyone,
This post will help you further enhance your app by creating a simple location tracking app with Flutter, allowing users to explore key features like GPS activation, location permission, and real-time location tracking
First, we will add the necessary packages.
flutter pub add location
flutter pub add permission_handler
Then we will get the permissions.
android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Let’s add the following methods to check if the user has GPS enabled:
void checkStatus() async {
bool _permissionGranted = await isPermissionGranted();
bool _gpsEnabled = await isGpsEnabled();
setState(() {
permissionGranted = _permissionGranted;
gpsEnabled = _gpsEnabled;
});
}
Future<bool> isPermissionGranted() async {
return await Permission.locationWhenInUse.isGranted;
}
Future<bool> isGpsEnabled() async {
return await Permission.location.serviceStatus.isEnabled;
}
If GPS is not enabled, let’s ask the user to enable it:
void requestEnableGps() async {
if (gpsEnabled) {
log("Already open");
} else {
bool isGpsActive = await location.requestService();
if (!isGpsActive) {
setState(() {
gpsEnabled = false;
});
log("User did not turn on GPS");
} else {
log("gave permission to the user and opened it");
setState(() {
gpsEnabled = true;
});
}
}
}
The application cannot track location without obtaining location permission. If there is no permission, let’s ask the user for permission:
void requestLocationPermission() async {
PermissionStatus permissionStatus =
await Permission.locationWhenInUse.request();
if (permissionStatus == PermissionStatus.granted) {
setState(() {
permissionGranted = true;
});
} else {
setState(() {
permissionGranted = false;
});
}
}
Once location permission and GPS activation are provided, we can start or stop location tracking:
void startTracking() async {
if (!(await isGpsEnabled())) {
return;
}
if (!(await isPermissionGranted())) {
return;
}
subscription = location.onLocationChanged.listen((event) {
addLocation(event);
});
setState(() {
trackingEnabled = true;
});
}
void stopTracking() {
subscription.cancel();
setState(() {
trackingEnabled = false;
});
clearLocation();
}
}
The application can store instant location settings and offer users the opportunity to display this data.
List<l.LocationData> locations = [];
void addLocation(l.LocationData data) {
setState(() {
locations.insert(0, data);
});
}
void clearLocation() {
setState(() {
locations.clear();
});
}
Finally, let’s create the user interface (Full Code):
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:location/location.dart' as l;
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const GetMaterialApp(
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool gpsEnabled = false;
bool permissionGranted = false;
l.Location location = l.Location();
late StreamSubscription subscription;
bool trackingEnabled = false;
List<l.LocationData> locations = [];
@override
void initState() {
super.initState();
checkStatus();
}
@override
void dispose() {
stopTracking();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Location App'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
buildListTile(
"GPS",
gpsEnabled
? const Text("Okey")
: ElevatedButton(
onPressed: () {
requestEnableGps();
},
child: const Text("Enable Gps")),
),
buildListTile(
"Permission",
permissionGranted
? const Text("Okey")
: ElevatedButton(
onPressed: () {
requestLocationPermission();
},
child: const Text("Request Permission")),
),
buildListTile(
"Location",
trackingEnabled
? ElevatedButton(
onPressed: () {
stopTracking();
},
child: const Text("Stop"))
: ElevatedButton(
onPressed: gpsEnabled && permissionGranted
? () {
startTracking();
}
: null,
child: const Text("Start")),
),
Expanded(
child: ListView.builder(
itemCount: locations.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
"${locations[index].latitude} ${locations[index].longitude}"),
);
},
))
],
),
),
);
}
ListTile buildListTile(
String title,
Widget? trailing,
) {
return ListTile(
dense: true,
title: Text(title),
trailing: trailing,
);
}
void requestEnableGps() async {
if (gpsEnabled) {
log("Already open");
} else {
bool isGpsActive = await location.requestService();
if (!isGpsActive) {
setState(() {
gpsEnabled = false;
});
log("User did not turn on GPS");
} else {
log("gave permission to the user and opened it");
setState(() {
gpsEnabled = true;
});
}
}
}
void requestLocationPermission() async {
PermissionStatus permissionStatus =
await Permission.locationWhenInUse.request();
if (permissionStatus == PermissionStatus.granted) {
setState(() {
permissionGranted = true;
});
} else {
setState(() {
permissionGranted = false;
});
}
}
Future<bool> isPermissionGranted() async {
return await Permission.locationWhenInUse.isGranted;
}
Future<bool> isGpsEnabled() async {
return await Permission.location.serviceStatus.isEnabled;
}
checkStatus() async {
bool _permissionGranted = await isPermissionGranted();
bool _gpsEnabled = await isGpsEnabled();
setState(() {
permissionGranted = _permissionGranted;
gpsEnabled = _gpsEnabled;
});
}
addLocation(l.LocationData data) {
setState(() {
locations.insert(0, data);
});
}
clearLocation() {
setState(() {
locations.clear();
});
}
void startTracking() async {
if (!(await isGpsEnabled())) {
return;
}
if (!(await isPermissionGranted())) {
return;
}
subscription = location.onLocationChanged.listen((event) {
addLocation(event);
});
setState(() {
trackingEnabled = true;
});
}
void stopTracking() {
subscription.cancel();
setState(() {
trackingEnabled = false;
});
clearLocation();
}
}
Github: