当用户单击不允许时,我正在使用各种插件来获取用户数据、联系人、照片和相机,应用程序会静默。
当用户选中“不再询问”和“不允许”并再次进入应用程序时,我想向用户显示“询问权限”对话框。
目前,当用户选中不允许时,应用程序不再要求
我知道用户必须授予应用程序访问个人信息的权限,包括 当前位置 , 相机 , 日历 , 联系方式 , 媒体库 , 麦克风 , 传感器 , 演讲 和照片。尽管人们喜欢使用可以访问这些信息的应用程序的便利性,但他们也希望能够控制他们的私有(private)数据。例如,人们喜欢能够自动标记照片与他们的实际位置或找到附近的 friend ,但他们也希望选择禁用这些功能。
如何在 flutter 中再次请求用户许可?
最佳答案
为简单起见,我使用了位置权限。要请求另一个权限,只需将 location 替换为该权限。这里是 list of all permissions .
1.安卓设置:
android/grade.properties
文件:android.useAndroidX=true
android.enableJetifier=true
android/app/build.gradle
文件:android {
compileSdkVersion 30 // Set this to at least 30
...
}
android/app/src/main/AndroidManifest.xml
文件<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
2.iOS设置:
info.plist
文件:<key>NSLocationWhenInUseUsageDescription</key>
<string>App needs location permission to work</string>
PERMISSION_LOCATION=1
至Podfile
:post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## Add the following line.
'PERMISSION_LOCATION=1'
]
end
end
end
3. flutter 设置:
将此添加到
pubspec.yaml
文件:permission_handler: ^8.0.0+2
主要工作:检查位置(即 GPS)是否已打开。
final serviceStatus = await Permission.locationWhenInUse.serviceStatus;
bool isGpsOn = serviceStatus == ServiceStatus.enabled;
final status = await Permission.locationWhenInUse.request();
if (status == PermissionStatus.granted) {
print('Permission granted');
} else if (status == PermissionStatus.denied) {
print('Denied. Show a dialog with a reason and again ask for the permission.');
} else if (status == PermissionStatus.permanentlyDenied) {
print('Take the user to the settings page.');
}
完整代码:
class HomePage extends StatelessWidget {
Future<void> _checkPermission() async {
final serviceStatus = await Permission.locationWhenInUse.serviceStatus;
final isGpsOn = serviceStatus == ServiceStatus.enabled;
if (!isGpsOn) {
print('Turn on location services before requesting permission.');
return;
}
final status = await Permission.locationWhenInUse.request();
if (status == PermissionStatus.granted) {
print('Permission granted');
} else if (status == PermissionStatus.denied) {
print('Permission denied. Show a dialog and again ask for the permission');
} else if (status == PermissionStatus.permanentlyDenied) {
print('Take the user to the settings page.');
await openAppSettings();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: _checkPermission,
child: Text('Check Permission'),
),
),
);
}
}
关于flutter - 如何在 Flutter 中请求和检查权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64646085/