Unhandled Exception: PlatformException(PERMISSION_DENIED, Access to location data denied, null) - flutter

it give the exception when i get the current location of the user . my flutter version :-
v1.17.4, and my info.plist code is given below. geolocator: ^5.3.2+2
Future<Position> locateUser() async {
return await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.low,locationPermissionLevel:
GeolocationPermission.location);
}
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>

It might be late to reply but I was also facing the same problem where the app was not asking for permission in iOS and was working perfectly fine in android.
Because it was not asked for permission that's why the permission code was not working for iOS. I found a package named "location_permissions" which can be used to ask for permission manually.
Steps to do are following
Add "location_permissions: 3.0.0+1" this dependencies in "pubspec.yaml". Please note that I did that for flutter 1.22.0 so for flutter 2.0 this might be an issue.
Import the package in the file
import 'package:location_permissions/location_permissions.dart';
Add the following code on the page where you want to ask for permission. (Better to add that on the very first page of your app.)
#override
void initState() {
....
if (Platform.isIOS) {
location_permission();
}
....
}
Add the following two methods in the same file
void location_permission() async {
final PermissionStatus permission = await _getLocationPermission();
if (permission == PermissionStatus.granted) {
final position = await geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
// Use the position to do whatever...
}
}
Future<PermissionStatus> _getLocationPermission() async {
final PermissionStatus permission = await LocationPermissions()
.checkPermissionStatus(level: LocationPermissionLevel.location);
if (permission != PermissionStatus.granted) {
final PermissionStatus permissionStatus = await LocationPermissions()
.requestPermissions(
permissionLevel: LocationPermissionLevel.location);
return permissionStatus;
} else {
return permission;
}
}
That's it now you should get a popup in the iOS app which will ask for the permission of location.

I was facing the same issue. I was running on IOS simulator
Issue Resolved on calling requestPermission() method
LocationPermission permission = await Geolocator.requestPermission();
Future<Position> position =
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
In info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location.</string>
dependency in pubspec.yaml:
geolocator: ^8.0.5

Related

Find Address From Coordinates

final addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
selectedAddress = addresses.first;
The plugin geocoder uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Use [geolocator][1] package and write the below code to get the city name and coordinates
void main() async {
await configureInjection(Environment.dev);
WidgetsFlutterBinding.ensureInitialized();
Position _currentPosition = await getCurrentPosition();
List<Placemark> placemarks = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = placemarks[0];
runApp(AppWidget());
}
Future<Position> getCurrentPosition() async {
bool serviceEnabled;
LocationPermission permission;
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(
'Location permissions are permanently denied, we cannot request permissions.');
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
);
}

Use getPositionStream to add location indicator Flutter

I have a HERE map with various functionality operating fine
I have a location indicator that currently operates Geolocator.getCurrentPosition(); which works fine, taking the lat,long and heading to place indicator.
I want it to update with users location from device.
I need to use Geolocator.getPositionStream to achieve this but after trying the implementation example online I'm stuck as it has different requirements to Current Position and the code won't work
Here is the LocationIndicator method, set to getRandom
void _addLocationIndicator(GeoCoordinates geoCoordinates, LocationIndicatorIndicatorStyle indicatorStyle) {
LocationIndicator locationIndicator = LocationIndicator();
locationIndicator.locationIndicatorStyle = indicatorStyle;
Location location = Location.withCoordinates(geoCoordinates);
location.time = DateTime.now();
location.bearingInDegrees = _getRandom(0, 360);
locationIndicator.updateLocation(location);
_hereMapController.addLifecycleListener(locationIndicator);
}
This is the given code for Stream
final LocationSettings locationSettings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
(Position position) {
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
This is the Current Location example which I have used and it works fine for current location
import 'package:geolocator/geolocator.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
Thanks

Flutter Error: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord

I needed to import contacts from mobile, and I used contacts_service from pub.dev. Then I made the changes required in AndroidManifest.xml for android and in info.plist for iOS, i.e, added the required permission, still I am getting this error when I am trying to read contacts from phone.
Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord
I resolved this issue, by requesting permission from the user, like this,
#override
void initState() {
super.initState();
getContacts();
}
// Function to get permission from the user
_contactsPermissions() async {
PermissionStatus permission = await Permission.contacts.status;
if (permission != PermissionStatus.granted && permission != PermissionStatus.denied) {
Map<Permission, PermissionStatus> permissionStatus = await [Permission.contacts].request();
return permissionStatus[Permission.contacts] ?? PermissionStatus.undetermined;
} else {
return permission;
}
}
//Function to import contacts
getContacts() async {
PermissionStatus contactsPermissionsStatus = await _contactsPermissions();
if (contactsPermissionsStatus == PermissionStatus.granted) {
List<Contact> _contacts = (await ContactsService.getContacts(withThumbnails: false)).toList();
setState(() {
contacts = _contacts;
});
}
}

Permisson handler - location do not work (Flutter)

I have a problem with Permisson Handler while try to use location.
When i tap and run gps func everything seems fine. Pop up is showing up I can choose options - Allow, Allow while Using etc, however when I choose allow or allow while it do not turn on location. It was working perfectly and just stopped somehow (permission is set to granted).
When I turn it on manually (Location on my device) everything is like it was before. I don't now why this prompt stops turning on location service.
void _onGpsTap() async {
bloc.emitEvent(DisplayProgressIndicator());
try {
permissionStatus = await Permission.location.status;
if (permissionStatus.isUndetermined) {
permissionStatus = await Permission.location.request(); // Here I'm asking for turning location on
}
if (permissionStatus.isDenied) {...
I'm using
geolocator: ^5.3.1
permission_handler: 5.0.0+hotfix.3
Try out below code:-
var status = await Permission.location.request();
if(status.isGranted){
log("Permission Granted");
getAddress();
}
getAddress() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
latitude = position.latitude;
longitude = position.longitude;
if(latitude != null && longitude != null){
apiCall();
}
}
permission_handler: ^8.1.4+2
geolocator: ^7.2.0+1
I found out that is not possible to turn on location service via. flutter and the user have to do it maunally.

How to get android mobile IMEI number using Dart language in Flutter?

I need to get android mobile IMEI number using Dart language in Flutter. How to get this slot1 or slot2 IMEI number from Android mobiles.
You could use device_information package. For this package to use you need to ask for phone permission from the user. So add the below permission in your Manifest file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
The second step is to get the user's permission to access their phone's info. Check the below code for permission:
Future<String> _askingPhonePermission() async {
final PermissionStatus permissionStatus = await _getPhonePermission();
}
Future<PermissionStatus> _getPhonePermission() async {
final PermissionStatus permission = await Permission.phone.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.phone].request();
return permissionStatus[Permission.phone] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}
And finally, use the above-mentioned package to extract the device's IMEI number.
String imeiNo = await DeviceInformation.deviceIMEINumber;