flutter - 如何在 flutter 中处理 "Permission Denied"异常?

标签 flutter dart

我正在尝试通过我的 flutter 应用程序获取 android 设备上存在的所有文件和目录的名称/路径。
以下是用于获取所需数据的代码:

Directory(_storageInstance.rootDirectory).list(recursive: true).listen((event) {
          _storageInstance.searchList.add(SearchEntity(path: event.path,type: event.runtimeType.toString() == "_Directory" ? EntityType.DIRECTORY : EntityType.FILE));
        });
现在我面临的问题是具有 的设备API 30 或以上 不允许访问某些特定目录,例如“Android”目录中的“data”和“obb”目录。
因此,在上面的代码中,每当我的 Directory().list().listen() 流接收到这些目录时,它都会引发以下异常:
E/flutter (28808): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: FileSystemException: Directory listing failed, path = '/storage/emulated/0/Android/data' (OS Error: Permission denied, errno = 13)
E/flutter (28808):
E/flutter (28808): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: FileSystemException: Directory listing failed, path = '/storage/emulated/0/Android/obb' (OS Error: Permission denied, errno = 13)
我尝试像这样添加try catch:
Directory(_storageInstance.rootDirectory).list(recursive: true).listen((event) {
          try{
            _storageInstance.searchList.add(SearchEntity(path: event.path,type: 
            event.runtimeType.toString() == "_Directory" ? EntityType.DIRECTORY : EntityType.FILE));
          }
          catch(e){
            print("Exception Caught");
          }
});
但它仍然无法处理异常并抛出与上述相同的异常。
通常是一个简单的 try catch 工作......也许我在这种情况下正确使用它。
在这种情况下如何正确处理异常?
提前感谢您的回答:)
更新:
我尝试在 Android Manifest.xml 中添加权限。但它仍然抛出相同的异常。
以下是应用程序的设置选项卡:
enter image description here
enter image description here

最佳答案

mainifest 中添加这一行标签:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
您必须在 android/app/src/debug/AndroidMainifest.xml 中添加这行代码这是调试版本和android/app/src/main/AndroidMainifest.xml .
所以,
<manifest ...>
   // Here must be lots of other codes 

   // Paste those lines after all those codes, here just above </mainifest>
</manifest>
如果还不清楚。这是 AndroidMainifest.xml 的示例来自我在 debug 中的项目目录。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.do_app">
    <!-- Flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
*注意:- 进行这些更改后,您必须从头开始运行。

关于flutter - 如何在 flutter 中处理 "Permission Denied"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63324680/

相关文章:

android - 在 flutter 中导入下拉依赖项 : ^ 1. 0.2 时出现问题

ios - Flutter项目在ios13上运行

firebase - 如何使用graphql从Firebase使用flutter从Cloud Firestore获取数据?

dart - 如何在 Dart 中通过 HttpServer 发送图像文件?

flutter - 如何检查用户是否向左或向右挥动(可忽略) flutter

flutter - 在 flutter 的容器底部添加阴影?

flutter - flutter 的旋转文本无法填充可用空间

Flutter 将应用栏标题向左偏移

firebase - Flutter Firebase Realtime数据库获取单个数据查询结果值null

flutter - Riverpod,在 BuildContext 和 Provider 之外读取状态