2
\$\begingroup\$

I'm using the flutter_simple_permissions plugin to request permission to read contacts on my flutter application. I want the app to quit when a user denies the permission, and need to show them a custom Dialog.

 Future<bool> getContactsPermission() async{
    bool hasPermission =  await SimplePermissions.checkPermission(Permission.ReadContacts);
      if(!hasPermission){
        await showDialog(context: context, builder: (context) {
          return new AlertDialog(
            title: Text('Requires Contacts Permission'),
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text('This application requires access to your contacts'),
                  Text('Please allow access'),
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Allow'),
                onPressed:() async {
                  final response = await SimplePermissions.requestPermission(Permission.ReadContacts);
                  if(response != PermissionStatus.authorized){
                    return false;
                  }
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('Exit App'),
                onPressed: () {
                  exit(0);
                },
              ),
            ],
          );
        });
    }

    return true;
  }


  refreshContacts() async {
    bool hasPermission = false;
    while(!hasPermission){
      hasPermission = await getContactsPermission();
    }

    var contacts = await ContactsService.getContacts();
    print("GOT CONTACTS!");
    setState(() {
      _contacts = contacts;
    });

  }

Whenever I call refreshContacts() the popup shows up if the user had no permission.

The code is working great, but I feel it could have been much simpler using FutureBuilder maybe?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.