In today’s mobile applications, accessing location services has become a fundamental feature for various functionalities such as mapping, weather updates, and location-based recommendations.
Checking Permissions
Before accessing the user’s location, your app must request the necessary permissions from the user
Their are three ways through which OS of mobile let user decides for location sharing permissions
- Share one time location
- Share location while using app, means you can access location everywhere in the app while using.
- User has denied request, you cannot get user location
Managing Location Permissions
Let’s add Geolocator package in your Flutter project, you need to add the dependency to your pubspec.yaml
file. This pacakge let user access his current location and also provide dynamic functions to check user locations status
dependencies:
flutter:
sdk: flutter
geolocator: ^10.1.0
iPhone Permission:
Add these permission into your info.plist file and explain the purpose of you need location access
<key>NSLocationAlwaysAndWhenInUsageDescription</key>
<string>App app want's to access your location to get address</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App app want's to access your location to get address.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>App app want's to access your location to get address.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App want's to access your location to get address.</string>
Android Permission:
Add these permission into your manifest file, android OS used these permission to trigger dialog during run time
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Requesting Permission:
Now you can call this functions any where in the app to check permission and take action. You can also open app setting your different packages.
// function to check if user has granted location permissions are
Future<bool> requestLocationPermission() 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 false;
}
}
if (permission == LocationPermission.deniedForever) {
return false ;
}
return true ;
}
Thank you for reading this, do leave your feedback if it helped.