当前位置: 首页 > 知识库问答 >
问题:

颤振:在屏幕开始处实现权限处理程序

上官波鸿
2023-03-14

Permission\u处理程序。飞奔

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:status_saver/utils/splash_screen.dart';

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

  @override
  _PermissionHandlerState createState() => _PermissionHandlerState();
}

class _PermissionHandlerState extends State<PermissionHandler> {
  Future<Widget> permissionCheck() async {
    var permissionStatus = await Permission.storage.status;


    if (!permissionStatus.isGranted){
      await Permission.storage.request();

    }
     permissionStatus = await Permission.storage.status;
     if(permissionStatus.isGranted) return SplashScreen();
     else {
          return AlertDialog(
              title: Text('Permission Required'),  // To display the title it is optional
              content: Text('Cannot proceed without permission'),   // Message which will be pop up on the screen
              // Action widget which will provide the user to acknowledge the choice
                actions: [
                TextButton(           // FlatButton widget is used to make a text to work like a button
                  child: Text('Open App Settings'),
                  onPressed: () => openAppSettings(),   
                       // function used to perform after pressing the button
                ),
                
              ],
            );
            
     }
     
  }
  
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
          builder: (ctx, snapshot) {
            
            // Checking if future is resolved or not
            if (snapshot.connectionState == ConnectionState.done) {
              // If we got an error
               
              if (snapshot.hasError) {
                return Center(
                  child: Text(
                    '${snapshot.error} occured',
                    style: TextStyle(fontSize: 18),
                  ),
                );
  
                // if we got our data
              } else  {
                return snapshot.data as Widget;
              }
            }
  
            // Displaying LoadingSpinner to indicate waiting state
            return Center(
              child: CircularProgressIndicator(),
            );
          },
  
          // Future that needs to be resolved
          // inorder to display something on the Canvas
          future: permissionCheck(),
        );
  }
}

主要的飞奔

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:status_saver/services/permission_handler.dart';
import 'package:status_saver/utils/router.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Hello World',
      debugShowCheckedModeBanner: false,
      onGenerateRoute: AppRouter.generateRoute,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: PermissionHandler(),
    );
  }
}

>

  • 在应用程序开始时,我想请求存储权限我做了什么-创建类PermissionHandler并将其分配给属性

    PermissionHandler()-有状态小部件,应在完成其业务逻辑后触发splashscreen

    • 请求用户权限,直到用户授予它
    • 在应用程序启动时一次性请求权限,如果接受,则加载启动屏幕,否则会弹出一个新对话框,将用户带到应用程序设置
     return Center(
                  child: CircularProgressIndicator(),
                );
    
     [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(PermissionHandler.PermissionManager, A request for permissions is
    already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)., null, null)
    [        ] E/flutter (  787): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
    [        ] E/flutter (  787): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
    [        ] E/flutter (  787): <asynchronous suspension>
    [        ] E/flutter (  787): #2      MethodChannelPermissionHandler.requestPermissions
    (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:71:9)
    [        ] E/flutter (  787): <asynchronous suspension>
    [        ] E/flutter (  787): #3      _PermissionHandlerScreenState.permissionServices (package:status_saver/services/permission_handler.dart:38:50)
    [        ] E/flutter (  787): <asynchronous suspension>
    [        ] E/flutter (  787): #4      _PermissionHandlerScreenState.permissionServiceCall (package:status_saver/services/permission_handler.dart:19:5)
    [        ] E/flutter (  787): <asynchronous suspension>
    [        ] E/flutter (  787): 
    
    
    

    按下拒绝按钮时引发错误

    从应用程序设置授予权限后,抛出错误:清单中没有为以下内容定义权限:[]

    清单文件定义了存储权限,(我删除了相机和麦克风的代码以便于测试,因此它们不是问题)

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    
  • 共有1个答案

    孙修德
    2023-03-14

    请参考以下示例代码

    解决方案1:限制用户导航到任何其他路线/屏幕,而不允许所述的所有权限

    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) {
          await openAppSettings().then(
            (value) async {
              if (value) {
                if (await Permission.storage.status.isPermanentlyDenied == true &&
                    await Permission.storage.status.isGranted == false) {
                  openAppSettings();
                  // permissionServiceCall(); /* opens app settings until permission is granted */
                }
              }
            },
          );
        } else {
          if (statuses[Permission.storage].isDenied) {
            permissionServiceCall();
          }
        }
        if (statuses[Permission.microphone].isPermanentlyDenied) {
         await openAppSettings().then(
            (value) async {
              if (value) {
                if (await Permission.microphone.status.isPermanentlyDenied == true &&
                    await Permission.microphone.status.isGranted == false) {
                  openAppSettings();
                  // permissionServiceCall(); /* opens app settings until permission is granted */
                }
              }
            },
          );
        } else {
          if (statuses[Permission.microphone].isDenied) {
            permissionServiceCall();
            
          }
        }
    
        if (statuses[Permission.camera].isPermanentlyDenied) {
    await openAppSettings().then(
            (value) async {
              if (value) {
                if (await Permission.camera.status.isPermanentlyDenied == true &&
                    await Permission.camera.status.isGranted == false) {
                  openAppSettings();
                  // permissionServiceCall(); /* opens app settings until permission is granted */
                }
              }
            },
          );
          //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",
              ),
            ),
          ),
        );
      }
    }
    
    
    

    解决方案2:

    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) {
        
        return WillPopScope(
          onWillPop: () {
            SystemNavigator.pop();
          },
          child: Scaffold(
            body: Container(
              child: Center(
                child: InkWell(
                    onTap: () {
                      permissionServiceCall();
                    },
                    child: Text("Click here to enable Enable Permissions")),
              ),
            ),
          ),
        );
      }
    }
    
    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",
              ),
            ),
          ),
        );
      }
    }
    
     类似资料:
    • 我已经在活动中创建了处理程序。这个Hanlder负责在10秒后拍摄屏幕截图。在运行方法中,我使用了虽然(标志==true)和屏幕捕获util标志==false,但这卡住了我的活动。我不能工作。它把屏幕拍摄一遍又一遍的相同的图像,因为动作被卡住了。我如何可以工作与我的屏幕和我正在做的处理程序采取屏幕截图后10秒?而循环卡住了我的应用程序。 它可以拍照,但我无法进行我的活动。

    • 我有一个联系人列表,显示在API响应的Future Builder列表视图中,我在服务器中总共有23个联系人,但我想去掉其名字和姓氏为NULL的所有联系人。 在处理空异常之前:单击此处 代码: 处理空异常后:单击此处 正如您从添加的代码和图像中看到的,为了处理异常,我只为所有名为null的联系人返回了一个空的容器,但现在我想更改它。我如何才能使那些名为firstname和lastname的联系人不

    • 我在开发一个应用程序,我不能收到通知时,电话锁定的FCM。 我使用了firebase和Awesome通知插件来显示通知。 有人能帮帮我吗,我困在这里谢谢

    • 一、权限处理分类 由上图可以看出,主要分为四类。下表逐一介绍各类对应的一些情况。 二、动态权限申请 虽然总的来说分为四类,但是只需要处理一种情况,即动态申请权限。其他三种情况,要么默认实现,要么系统定制,无法从代码角度进行调整。那么下面先来看下那些权限需要动态申请。 (1)权限列表 Android6.0以上把权限分为普通权限和危险权限,所以危险权限是需要动态申请,给予用户提示的,而危险权限就是上表

    • 我对颤振世界还不熟悉,我犯了一个我不能完全理解的错误。 这是我的netwrok处理程序代码 这是我的代码,我调用网络处理器的获取方法 我得到了这个错误 [错误:flatter/lib/ui/ui\u dart\u state.cc(209)]未处理的异常:类型'\u InternalLinkedHashMap 谁能帮帮我吗?

    • 我正在调用一个post API,在该API中,我必须发送FormData,但在接收到响应后,当我尝试解析该响应时,我得到了以下异常。 我得到以下错误: 下面是我的模型课https://gist.github.com/achinverma/641774f50d27b2f4f5be9f1c341f0fc2