September 6, 2021

How to request and check permissions in Flutter

By lj

Request permission

Before requesting permission we need to confirm first, do we need to ask for permission or use intents. Sometime it is okay to use intent but sometime we need permission. I-phone can’t give access to users private information, also android can’t. So there is concept called run-time permission. To request permission we will use permission_handler package from pub.dev .

Add permission_handler package

dependencies:
  permission_handler: ^8.1.4+2

Now we need to check permission, I am using this package for contacts permission read contacts from device. Please note that you might need to setup things like adding permission in Manifest.xml for android and for IOS there might be other setup. Do proper setup and use Permission class from this package to check and request permission.

void checkPermission() async{
  final PermissionStatus permissionStatus = await Permission.contacts.status;
  print("permission  - $permissionStatus");
  if(permissionStatus == PermissionStatus.limited || permissionStatus == PermissionStatus.granted){

  } else if(permissionStatus == PermissionStatus.denied){
    await Permission.contacts.request();
    checkPermission();
  } else if(permissionStatus == PermissionStatus.permanentlyDenied){

  } else if(permissionStatus == PermissionStatus.restricted){

  }
}

Here checking contact permission, If permission is denied this will automatically ask for permission. You can also setup for status like restricted. I have read details for status from the package itself, which I have described below:

denied

The user denied access to requested feature. This is also default status.

granted

As name suggest, it comes when user granted access.

restricted

When the OS denies to requested feature. The user can not change this, due to parental control.

limited

User have granted limited access to this feature.

permanentlyDenied

User have denied request and checked do not show checkbox.