Hello everyone. Here we are back with a new article in which we’ll see how we can effectively handle permissions in our flutter application. For this we have to add a package from pub.dev which is called permission_handler 

Permission handler is really easily to use in our flutter application. As we have a number of permissions in our single app, we can easily get a status of any permission during run time. There are couple of methods that we can easily use and all are described below: 

  • Checking status for a specific permission 

We can easily get to know status of a permission by calling status method, which will return status of that specific permission as one of value as below:

undetermined, granted, denied, restricted, permanentlyDenied 

i.e If we want to check Camera permission, we can simply use: 

Permission.camera.status  

  • Request for a specific permission 

Requesting a permission is as easy as knowing status of a specific permission. Calling request() method for that specific permission will ask user to grant that specific permissionOne thing that we should keep in mind that, if permission is already granted before nothing is going to happen. So, we should first check permission status and then we can ask for that specific permission.  

i.e If we want to ask Camera permission, we can simply call:

Permission.camera.request() 

  • Handling a call-back after requesting a Permission to the user 

When permission is being asked, we can wait for action from user side using await keyword to get status of isGranted  parameter. This parameter will return a Boolean value basis on which we can move forward in our Flutter application.  

i.e We can wait for User’s response for camera permission as below: 

await Permission.camera.request().isGranted 

Let’s see practically how we can implement this with minimum code. In this small application, we’re going to perform steps as below, 

  1. Check status for Camera Permission & Print an appropriate permission status on screen  
  2. If it’s not granted ask for Camera Permission 
  3. When user grant it, we’ll update permission status displayed on the screen 

Let’s begin by creating a fresh new flutter project and extending our ready to use code as below. 

Step 1 

First of all, we have to add a package in pubspec.yaml file specified as below:

permission_handler: ^5.0.1+1 

This will give us access to parameter like statusisGranted & method request() to call for a specific permission. 

Step 2 

Modify our main() method and MyApp widget as shown below:

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: AppHome(),
    );
  }
}

Step 3 

Take a PermissionStatus paramter in AppHomeState class as below:

PermissionStatus _permissionStatus; 

Add/Update initState() method as below, 

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback(onLayoutDone);
}

void onLayoutDone(Duration timeStampasync {
  _permissionStatus await Permission.camera.status;
  setState(() {});
} 

Let’s take a look what this will do. Here we’re adding a call-back which will be called after last frame rednered. In onLayoutDone method we’re checking camera permission status & performing a setState will update parameter value & re-render the screen. 

So initially, whatever the status of Camera permission (obviously, it will be undetermined) it will be displayed in centre of the screen using below code:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('SFL Flutter Permission Article'),
    ),
    body: Padding(
      padding: EdgeInsets.all(16.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '$_permissionStatus',
            style: Theme.of(context).textTheme.headline5,
          ),
        ],
      ),
    ),
  );
}

Step 4 

Now as we know, initially permission will be undetermined hence some way we have to ask user to grant Camera permission. So, to do that let’s have a RaisedButton below displayed permission status as shown below. 

RaisedButton(
  child: Padding(
    padding: const EdgeInsets.symmetric(
      vertical: 14.0,
    ),
    child: Text(
      'Request Permission',
      style: TextStyle(
        color: Colors.white,
        fontSize: 16.0,
      ),
    ),
  ),
  color: Colors.lightBlue,
  onPressed: () {
    _askCameraPermission();
  },
),

When user click on it, it will call _askCameraPermission() method which will ask for Camera permission to user as shown below code:

void _askCameraPermission() async {
  if (await Permission.camera.request().isGranted) {
    _permissionStatus = await Permission.camera.status;
    setState(() {});
  }
}

This method will use request() method to ask for Camera permission and it will wait to get response for user using await keyword to check updated value of isGranted parameter. If user grant camera permission it will return true for isGranted or else it will return false. So, based on the response we can move forward in application using if…else… loop structure. 

Now if user grants permission for Camera, we’ll simply update _permissionStatus parameter by getting its status using same await Permission.camera.status call. 

Step 5 

Most important step that we have to follow is, whatever permission that we’re going to ask from our flutter app we have to mention that in Info.plist file for iOS module and AndroidManifest.xml file for Android module. 

For Camera, in Info.plist file mention a message for Privacy – Camera Usage Description for iOS module and specify below permission usage in AndroidManifest.xml file for Android module. 

<uses-permission android:name=”android.permission.CAMERA” /> 

After mentioning these two things, now we’re able to see how our application will work. 

So, this is how we can check status for a specific permission & request for a permission if its status has not been granted yet. One important thing is that, if the permission has been already granted, we have to make code flow in way where we can check status first and on the basis of this status we’ll move forward in our application. To know more, how we can handle application workflow in specified way, wait for our next article of this series.

Related Posts

Power BI Experts & Dynamic Dashboards: Decrypting AMOT’s Business Success Story

Discover how AMOT, a top manufacturing company, transformed raw financial data into actionable business insights using dynamic dashboards.

Power BI Financial Dashboards for Optimal Fiscal Management

Power BI Financial Dashboard will uplift your financial story by providing your team with intuitive analytics, uncovering hidden trends,…

Power BI Service Desk Dashboard: The Next Level of IT Support

Power BI Service Desk Dashboard offers deep insights for best customer service. Explore how this innovative tool can reform your approach…

Get a FREE estimate for your project today.

Our team of experts will review your project and give you a quote at no cost.

Get a quote on your project!