Get permission in flutter

 

First, add permission handeler package in your .yaml file

permission_handler: ^3.1.0

Then, make this class in your project

in this example, I am using camera permission for example you can change this.

 

import 'package:permission_handler/permission_handler.dart';

class PermissionsService {
  final PermissionHandler _permissionHandler = PermissionHandler();

  Future _requestPermission(PermissionGroup permission) async {
    var result = await _permissionHandler.requestPermissions([permission]);
    if (result[permission] == PermissionStatus.granted) {
      return true;
    }
    return false;
  }

  Future requestContactsPermission() async {
    return _requestPermission(PermissionGroup.camera);
  }

  Future onPermissionDenied({Function onPermissionDenied}) async {
    var granted = await _requestPermission(PermissionGroup.camera);
    if (!granted) {
      onPermissionDenied();
    }
    return granted;
  }

  Future hasContactsPermission() async {
    return hasPermission(PermissionGroup.camera);
  }

  Future hasPermission(PermissionGroup permission) async {
    var permissionStatus =
        await _permissionHandler.checkPermissionStatus(permission);
    return permissionStatus == PermissionStatus.granted;
  }
}

Then use this class on your page to get permission

  @override
  void initState() {
    super.initState();
    PermissionsService().requestContactsPermission();
  }

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime