我正在使用工作正常的permission_handler,但现在我需要知道某个
Permission
之前是否已经是requested
。
所以我正在寻找类似
PermissionStatus.notDetermined
的东西。这个套餐提供类似的东西吗?我找不到它,但至少对我来说这是一件非常重要的事情。
我知道
firebase_messaging
包中有类似的东西。
如果之前未请求过 systemPermissionStatus,我只想显示一个弹出窗口。
这当然也可以通过在
SharedPreferences
中保存一些值来完成,例如“wasRequested”,但我认为这个用例必须有一个现有的函数?
如果您需要更多信息,请告诉我。
更新
我还注意到
status
和从 status
返回的 .request
是不同的。
这对我来说没有任何意义,这太令人困惑了。
final stat = await Permission.notification.status; // -> denied
final req = await Permission.notification.request(); // -> permanentlyDenied
您可以在文档的如何使用部分中看到第一个示例,它使用
Permission.camera.status.isDenied
来确定权限是否被拒绝或尚未询问。代码注释中这么说:
if (status.isDenied) {
// We haven't asked for permission yet or the permission has been denied before, but not permanently.
}
所以您可以使用
作为您的isDenied
。notDetermined
我提供了使用
isDenied
来调节弹出窗口的示例代码
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
class PermissionHandlerPage extends StatefulWidget {
const PermissionHandlerPage({super.key});
@override
State<PermissionHandlerPage> createState() => _PermissionHandlerPageState();
}
class _PermissionHandlerPageState extends State<PermissionHandlerPage> {
String status = '-';
void _showRequestPermissionDialog() {
AlertDialog alert(BuildContext context) {
Widget title = const Text('Permission');
Widget content = const Text(
'This application need location permission to run.',
);
Widget cancel = OutlinedButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
);
Future<void> handleRequest() async {
// Request [locationWhenInUse] permission.
final status = await Permission.locationWhenInUse.request();
this.status = status.name;
setState(() {});
}
Widget request = ElevatedButton(
onPressed: handleRequest,
child: const Text('Request Permission'),
);
return AlertDialog(
title: title,
content: content,
actions: [cancel, request],
);
}
showDialog(context: context, builder: alert);
}
Future<void> _checkPermission() async {
final status = await Permission.location.status;
if (status.isDenied) {
// [Permission.location.status] As per official documentation:
// "We haven't asked for permission yet or the permission has been
// denied before, but not permanently."
//
// https://pub.dev/packages/permission_handler
print('Permission is denied or not asked yet.');
// Show dialog to inform user that permission not granted yet.
_showRequestPermissionDialog();
} else if (status.isPermanentlyDenied) {
print('Permission is permanently denied');
} else if (status.isGranted) {
print('Permission granted');
}
this.status = status.name;
setState(() {});
}
@override
void initState() {
super.initState();
// Check permission at the first time page opened.
_checkPermission();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Permission Handler')),
body: SafeArea(
child: Center(
child: Text('Permission status: $status'),
),
),
);
}
}