tluanga hauhnar
tluanga hauhnar

Reputation: 91

using permission handler at main flutter

I am trying to get user permission at the start of the app inside main but i get and exception.

void main() async {
    final permission = Permission.manageExternalStorage.request();
    if (await permission.isGranted){
    }

Error:

Exception has occurred. _CastError (Null check operator used on a null value)

Upvotes: 0

Views: 2601

Answers (2)

Peter Koltai
Peter Koltai

Reputation: 9734

Check out the code below, I think it can solve your problem, I tested it and worked for me. Instead of getting the permission in main(), it uses the stateful widget MyApp, tries to get the permission in initState(), uses async function _getPermission() to await the user's response and with setState() updates the permission grant state in _permission member.

In the build method you can decide what your app should do if permission is granted or not. In this example I only output a single message depending on the permission. For example you can return your MaterialApp when granted, and a warning message if not, anything you like.

You might be aware of this, but one more thing: if the user permanently denies permission, this solution will not prompt again, so you have to handle this case, if your app cannot work without this, you can offer the user to go into settings and enable it there.

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _permission = false;

  void _getPermission() async {
    final grant = await Permission.camera.request().isGranted;
    setState(() {
      _permission = grant;
    });
  }

  @override
  void initState() {
    _getPermission();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String message =
        _permission ? 'Permission granted' : 'Permission not granted';

    return MaterialApp(home: Scaffold(body: Center(child: Text(message))));
  }
}

Upvotes: 1

Peter Koltai
Peter Koltai

Reputation: 9734

I don't know which package do you use for permission handling, but if you use this, you have to add request() before isGranted:

if (await Permission.manageExternalStorage.request().isGranted) {
}

Or if you want just to get permission status without asking for it:

var status = await Permission.manageExternalStorage.status;
if (status.isDenied) {
}

Upvotes: 0

Related Questions