How to ask for user permission in flutter

You can copy and adopt this source code example to your flutter project easily without issues.

add this code to your pubspec.yaml file

  permission_handler: ^3.0.1  

Create a ask_for_permission.dart file (use any name of your choice) and add this code:

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

class AskForPermission extends StatefulWidget {
  @override
  _AskForPermissionState createState() => _AskForPermissionState();
}

class _AskForPermissionState extends State<AskForPermission> {
  Map<PermissionGroup, PermissionStatus> permissions;
  @override
  void initState(){
    super.initState();
    getPermission();
  }

  void getPermission() async {
    permissions = await PermissionHandler().requestPermissions([
      PermissionGroup.location,
      PermissionGroup.camera,
      PermissionGroup.locationAlways,
      PermissionGroup.phone,
      PermissionGroup.sensors,
      PermissionGroup.storage,
      PermissionGroup.microphone,
    ]);


  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('Ask for permisions'),
          backgroundColor: Colors.red,
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text("All Permission Granted"),
            ],
          )
        ),
      
    );
  }
}

In your main.dart file (main entry point of the app), add this:

import 'package:inducesmile/ask_for_permission.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new AskForPermission(),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.