Member-only story
How to test GPS in Flutter
Using Android emulator
4 min readFeb 2, 2024
In the app I’m currently developing, I need to save the users’ current location. In addition, I need to check if the user is driving.
The excellent geolocator plugin is easy to use and has extensive documentation and examples. Creating a simple class that returns the current location and checks the current speed is trivial.
import 'package:geolocator/geolocator.dart';
import 'package:smellit/gps/location_exception.dart';
/// A service class for managing and utilizing location-based features.
class LocationService {
// Constant for the speed limit to determine if the user is driving.
static const double speedLimit = 2.5;//meter per second
/// Requests and checks the necessary permissions for location services.
static Future<bool> requestPermissions() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(…