颤动如何修复权限处理程序错误

Posted

技术标签:

【中文标题】颤动如何修复权限处理程序错误【英文标题】:flutter how to fix permission handler error 【发布时间】:2022-01-15 04:44:21 【问题描述】:

我不知道如何解决这个红色错误部分。 我从互联网上复制了这个然后我得到了这个错误。 请帮我解决这个问题。

这是我的完整代码。

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:android_intent/android_intent.dart';
import 'package:geolocator/geolocator.dart';
class AskForPermission extends StatefulWidget 
  @override
  _AskForPermissionState createState() => _AskForPermissionState();

class _AskForPermissionState extends State<AskForPermission> 
  final PermissionHandler permissionHandler = PermissionHandler();
  Map<PermissionGroup, PermissionStatus>? permissions;
  void initState() 
    super.initState();
    requestLocationPermission();
    _gpsService();
  
  Future<bool> _requestPermission(PermissionGroup permission) async 
    final PermissionHandler _permissionHandler = PermissionHandler();
    var result = await _permissionHandler.requestPermissions([permission]);
    if (result[permission] == PermissionStatus.granted) 
      return true;
    
    return false;
  
/*Checking if your App has been Given Permission*/
  Future<bool> requestLocationPermission(Function? onPermissionDenied) async 
    var granted = await _requestPermission(PermissionGroup.location);
    if (granted!=true) 
      requestLocationPermission();
    
    debugPrint('requestContactsPermission $granted');
    return granted;
  
/*Show dialog if GPS not enabled and open settings location*/
  Future _checkGps() async 
    if (!(await Geolocator.isLocationServiceEnabled())) 
      if (Theme.of(context).platform == TargetPlatform.android) 
        showDialog(
            context: context,
            builder: (BuildContext context) 
              return AlertDialog(
                title: Text("Can't get gurrent location"),
                content:const Text('Please make sure you enable GPS and try again'),
                actions: <Widget>[
                  FlatButton(child: Text('Ok'),
                      onPressed: () 
                        final AndroidIntent intent = AndroidIntent(
                            action: 'android.settings.LOCATION_SOURCE_SETTINGS');
                        intent.launch();
                        Navigator.of(context, rootNavigator: true).pop();
                        _gpsService();
                      )],
              );
            );
      
    
  

/*Check if gps service is enabled or not*/
  Future _gpsService() async 
    if (!(await Geolocator.isLocationServiceEnabled())) 
      _checkGps();
      return null;
     else
      return true;
  
  @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"),
              ],
            ))
    );
  


【问题讨论】:

这是 pub 权限处理程序中的包搜索 你在pubspec.yaml中添加了permission_handler吗? @PoojaPatil 是的,我添加了,但实际上这段代码是旧版本的权限处理程序,我在 yaml 文件中添加了新版本的权限处理程序 【参考方案1】:

安装权限处理程序包from here。然后在您的 .dart 文件中添加导入并在某处调用权限询问功能。例如。像这样的函数要求存储权限。

import 'package:permission_handler/permission_handler.dart';

  Future<void> getStoragePermission() async 
    if (await Permission.manageExternalStorage.request().isGranted) 
      setState(() );
     else if (await Permission.storage.request().isPermanentlyDenied) 
      await openAppSettings();
     else if (await Permission.storage.request().isDenied) 
      setState(() );
    
  

【讨论】:

【参考方案2】:

请参考以下代码

https://pub.dev/packages/permission_handler/install 权限处理程序:^5.0.1+1

import 'package:permission_handler/permission_handler.dart';
import 'package:google_fonts/google_fonts.dart';

class MyApp extends StatelessWidget 
  MyApp(Key key) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: Color(0xfff00B074),
        textTheme: const TextTheme(
          bodyText1: TextStyle(
              fontSize: 18.0,
              fontFamily: 'Barlow-Medium',
              color: Color(0xff464255)),
        ),
      ),
      home: PermissionHandlerScreen(),
    );
  


class PermissionHandlerScreen extends StatefulWidget 
  @override
  _PermissionHandlerScreenState createState() =>
      _PermissionHandlerScreenState();


class _PermissionHandlerScreenState extends State<PermissionHandlerScreen> 
  @override
  void initState() 
    super.initState();
    permissionServiceCall();
  

  permissionServiceCall() async 
    await permissionServices().then(
      (value) 
        if (value != null) 
          if (value[Permission.storage].isGranted &&
              value[Permission.camera].isGranted &&
              value[Permission.microphone].isGranted) 
            /* ========= New Screen Added  ============= */

            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => SplashScreen()),
            );
          
        
      ,
    );
  

  /*Permission services*/
  Future<Map<Permission, PermissionStatus>> permissionServices() async 
    // You can request multiple permissions at once.
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
      Permission.camera,
      Permission.microphone,
      //add more permission to request here.
    ].request();

    if (statuses[Permission.storage].isPermanentlyDenied) 
      openAppSettings();
      setState(() );
     else 
      if (statuses[Permission.storage].isDenied) 
        permissionServiceCall();
      
    
    if (statuses[Permission.microphone].isPermanentlyDenied) 
      openAppSettings();
      setState(() );
     else 
      if (statuses[Permission.microphone].isDenied) 
        permissionServiceCall();
        
      
    

    if (statuses[Permission.camera].isPermanentlyDenied) 
      openAppSettings();
      setState(() );
     else 
      if (statuses[Permission.camera].isDenied) 
        permissionServiceCall();
      
    
    /*Permission.camera: PermissionStatus.granted, Permission.storage: PermissionStatus.granted*/
    return statuses;
  

  @override
  Widget build(BuildContext context) 
    permissionServiceCall();
    return WillPopScope(
      onWillPop: () 
        SystemNavigator.pop();
      ,
      child: Scaffold(
        body: Container(
          child: Center(
            child: InkWell(
                onTap: () 
                  permissionServiceCall();
                ,
                child: Text("Click here to enable Enable Permission Screen")),
          ),
        ),
      ),
    );
  


class SplashScreen extends StatelessWidget 
  const SplashScreen(Key key) : super(key: key);

  @override
  Widget build(BuildContext context) 
    return WillPopScope(
      onWillPop: () 
        SystemNavigator.pop();
      ,
      child: Scaffold(
        body: Center(
          child: Text(
            "Splash Screen",
          ),
        ),
      ),
    );
  



【讨论】:

【参考方案3】:

在您的 pubspec.yaml 文件中添加 permission_handler 依赖项。

试试flutter pub get 命令。如果已经完成,请参考此链接了解permission handler package。

【讨论】:

【参考方案4】:

我遇到了同样的问题 - 在我升级到 ^8.3.0 后,与 permission_handler ^8.0.0+2 一起工作的代码不再工作 - 代码无法编译,权限和其他不能编译的类“找到”了(我使用 VS Code)

我通过清理 pub 缓存修复了它:

flutter pub cache clean

然后再次获取依赖项:

flutter pub get

PS:为了升级到 8.3.0,我在 build.gradle 文件中设置了 targetSdkVersion 和 compileSdkVersion 为 31

【讨论】:

以上是关于颤动如何修复权限处理程序错误的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤动中使用 bloc 模式进行错误处理?

如何修复在空颤动上调用的方法“包含密钥”[重复]

如何在颤动中处理 Firebase Auth 未处理的异常? [复制]

Flutter:如何修复页面控制器动画错误

一旦视图更改,颤动数字时钟小部件就会导致错误

类在firebase消息颤动上找不到异常