Request permissions from operating system is always a crucial part of development. Major question is why do we need permissions?

In general when we want to use resources from system like accessing files, using device locations, looking into contacts etc.. . We need to specify our system that our application is gonna use this resource. This is good for security reasons so that any third party app don’t access our data, without our knowing. But its little teasing for programmers especially for myself because I need to write some extra lines of code.

But don’t worry as a flutter developer we have a great pool of dependencies that are really efficient and we don’t need to write anything from scratch. Those packages are much efficient and reliable to use.

Let’s see how we can simply add permission feature to our highly professional and super hi-tech mobile applications. I tried to make as simple as possible just for beginners. But for professional developers like us, we can add additional conditions and functions to make it so called industry standard look.

Step-1: Installing dependency

For this purpose we are going to use permission_handler version 9.2.0. We can use any version but keep in mind if you are watching this tutorial so late in 2050 some functions maybe deprecated or discontinued. Many people get such issues. Generally upgrading version can solve this issue.

Why are we use using this package specifically? The reason is because it is pretty stable and more than 2000 developers trust it.

We can install this package by running this in terminal:

flutter pub add permission_handler

or by adding this line under dependencies in pubspec.yaml file:

dependencies:
  permission_handler: ^9.2.0

Importing package:

import 'package:permission_handler/permission_handler.dart';

Step-2: Making requests and handling response

Now we have successfully installed our dependency. Its time to use it. For this particular example we are gonna request for storage access and we will hack all mobile data.

We can access any resource by using Permission class. For example Permission.camera, Permission.bluetooth etc..

We use

Permission.storage

Getting permission status. Whether permission is granted, denied, resticted or denied permanently.

Permission.storage.status

As we need to wait for user. Until he ask from his family and friends to allow our app for accessing storage. We are using async function and storing our status in a variable.

Future requestPermission() async {
    var result = await Permission.storage.request();
}

We can also apply logical operations by using result variable.

Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");

    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return;
  }

Now finally its time to use this function. For this purpose I have created a statefull widget and button in center screen.

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

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: ElevatedButton(
                  onPressed: () {},
                  child: Text("Request")),
        )),
      ),
    );
  }
}

Calling our function final code will look like this

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

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  
  Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");
    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: ElevatedButton(
                  onPressed: () {
                    requestPermission();
                  },
                  child: Text("Request")),
        )),
      ),
    );
  }
}

We can apply some logic to do some actions when user finally agree to give us access their personal data.

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

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  bool permissionStatus = false;


  Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");
      setState(() {
        permissionStatus = true;
      });
    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return 0;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: permissionStatus
              ? Text("Permission Granted!")
              : ElevatedButton(
                  onPressed: () {
                    requestPermission();
                  },
                  child: Text("Request")),
        )),
      ),
    );
  }
}

Walla!!! Congratulations you are now able to get access to your user’s personal data. If you find this article helpful. Please provide your fruitful comment bellow.