Permission request in Flutter - flutter

How can I request permission for accessing the device microphone for recording audio in Flutter?
I have tried looking this up but haven't been able to find a clear answer.

You could do something like this:
await _askingPermission();
Future<String> _askingPermission() async {
final PermissionStatus permissionStatus =
await _getPhonePermission();
if (permissionStatus == PermissionStatus.granted){
//permission is granted
} else{
//permission denied or undermined
}
}
Future<PermissionStatus> _getPermission() async {
final PermissionStatus permission = await Permission.microphone.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.microphone].request();
return permissionStatus[Permission.microphone] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}

Add this line in your manifest file
<uses-permission android:name="android.permission.RECORD_AUDIO" />

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,
);
}

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;
});
}
}

How to handle "gps" location provider requires ACCESS_FINE_LOCATION permission. in flutter apps

Hi I am trying to get user location by using location package and google-maps-flutter in flutter.. but I get an error that say "gps" location provider requires ACCESS_FINE_LOCATION permission. I have added this code in my androidmanifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I still get an error although I have added that code..is there something that I should do to prevent this problem?
You should check your self permission status and If it did not granted by user, you should request for permission. You could use location plugin for request permissions.
https://pub.dev/packages/location
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
_locationData = await location.getLocation();

The method 'PermissionHandler' isn't defined for the class

After upgrading PermissionHandler to latest (5.0.0). The PermissionHandler() not found and also
The name 'PermissionGroup' isn't a type so it can't be used as a type argument..
Here is a code snippet:
PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
if (permission != PermissionStatus.granted && permission != PermissionStatus.neverAskAgain) {
Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
if (permissions.containsValue(2))
fileDownload(context, finalUrl);
}
What is the problem?
That because from permission_handler: ^5.0.0 the author BaseFlow made it more intuitive for us to use
as asked in this issue ticker (#230).
Your code snippet need to change like below:
if (await Permission.storage.request().isGranted) {
fileDownload(context, finalUrl);
}
So now those mapped like this:
old way new way
------- -------
await PermissionHandler()
.checkPermissionStatus(PermissionGroup.camera) await PermissionGroup.camera.status
await PermissionHandler().requestPermissions(
[PermissionGroup.camera]))[PermissionGroup.camera] await PermissionGroup.camera.request()
await PermissionHandler().requestPermissions(
[PermissionGroup.camera, PermissionGroup.storage])) await [PermissionGroup.camera, PermissionGroup.storage].request()
await PermissionHandler().checkServiceStatus
(PermissionGroup.location) await Permission.location.serviceStatus.isEnabled
Read more here: this issue ticker (#230).
Use permission_handler: ^3.0.0 ,it Worked for me
Those who are still struggling with this, please follow the instructions
The latest version for handling permissions is now
permission_handler: ^5.0.0+hotfix.8
Now I think they have changed the usage.
Use case: I have to give check contact permissions in order to save a contact in the phone directory. SO This works perfectly for me.
Future<void> saveContactInPhone() async {
try {
print("saving Conatct");
PermissionStatus permission = await Permission.contacts.status;
if (permission != PermissionStatus.granted) {
await Permission.contacts.request();
PermissionStatus permission = await Permission.contacts.status;
if (permission == PermissionStatus.granted) {
Contact newContact = new Contact();
newContact.givenName ="Ajay";
newContact.familyName ="abc";
newContact.phones = [Item(label: "mobile",value: "9998887771")];
await ContactsService.addContact(newContact);
} else {
//_handleInvalidPermissions(context);
}
} else {
Contact newContact = new Contact();
newContact.givenName ="Ajay";
newContact.familyName ="abc";
newContact.phones = [Item(label: "mobile",value: "9998887771")];
await ContactsService.addContact(newContact);
}
print("object");
} catch (e) {
print(e);
}
}
Please refer Permission_handler_example for more info
Please adhere to following config
pubspec.yaml
permission_handler: ^6.1.1
import
import 'package:permission_handler/permission_handler.dart';
check permissions like
if (await Permission.storage.request().isGranted) {
String dir = (await getExternalStorageDirectory()).absolute.path + "/documents";
}

Trying to write a permission for camera, microphone and map on flutter

Trying to write a permission code for camera, microphone and map on flutter
Here is the code, Please what is wrong with this code
its in a dart file which would accessible
class Permissions {
static Future<bool> cameraAndMicrophonePermissionsGranted() async {
PermissionStatus cameraPermissionStatus = await _getCameraPermission();
PermissionStatus microphonePermissionStatus =
await _getMicrophonePermission();
if (cameraPermissionStatus == PermissionStatus.granted &&
microphonePermissionStatus == PermissionStatus.granted) {
return true;
} else {
_handleInvalidPermissions(
cameraPermissionStatus, microphonePermissionStatus);
return false;
}
}
static Future<PermissionStatus> _getCameraPermission() async {
PermissionStatus permission =
await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.disabled) {
Map<PermissionGroup, PermissionStatus> permissionStatus =
await PermissionHandler()
.requestPermissions([PermissionGroup.camera]);
return permissionStatus[PermissionGroup.camera] ??
PermissionStatus.unknown;
} else {
return permission;
}
}
static Future<PermissionStatus> _getMicrophonePermission() async {
PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.microphone);
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.disabled) {
Map<PermissionGroup, PermissionStatus> permissionStatus =
await PermissionHandler()
.requestPermissions([PermissionGroup.microphone]);
return permissionStatus[PermissionGroup.microphone] ??
PermissionStatus.unknown;
} else {
return permission;
}
}
static void _handleInvalidPermissions(
PermissionStatus cameraPermissionStatus,
PermissionStatus microphonePermissionStatus,
) {
if (cameraPermissionStatus == PermissionStatus.denied &&
microphonePermissionStatus == PermissionStatus.denied) {
throw new PlatformException(
code: "PERMISSION_DENIED",
message: "Access to camera and microphone denied",
details: null);
} else if (cameraPermissionStatus == PermissionStatus.disabled &&
microphonePermissionStatus == PermissionStatus.disabled) {
throw new PlatformException(
code: "PERMISSION_DISABLED",
message: "Location data is not available on device",
details: null);
}
}
}
the errors are
method "PermissionHandler" is not defined in the class "Permissions"
Undefined name "PermissionGroup"
the getter 'disable' is not defined in the class PermissionStatus
the name "PermissionGroup" isn't a type so it cant be used as a type argument
Undefined name "disabled"
what can be wrong with this code?
Since Version
permission_handler 5.0.0
new methods of checking and requesting permissions are as follows
Old : await PermissionHandler() .checkPermissionStatus(PermissionGroup.camera)
New : await Permission.camera.status
Old : (await PermissionHandler() .requestPermissions([PermissionGroup.camera]))[PermissionGroup.camera]
New : await Permission.camera.request()
Old : await PermissionHandler() .requestPermissions([PermissionGroup.camera, PermissionGroup.storage]))
New : await [Permission.camera, PermissionGroup.storage].request()
Old : await PermissionHandler() .checkServiceStatus(PermissionGroup.location)
New : await Permission.location.serviceStatus.isEnabled
Your code use permission_handler 3.3.0
In pubspec.yaml , you must specify version 3.3.0
dependencies:
flutter:
sdk: flutter
permission_handler: 3.3.0