【问题标题】:How to handle "Permission Denied" Exception in flutter?如何处理flutter中的“Permission Denied”异常?
【发布时间】:2020-11-29 03:24:36
【问题描述】:

我正在尝试通过我的 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 中添加权限。但它仍然抛出相同的异常。

下面是应用的设置标签:

【问题讨论】:

  • 您是否通过添加androidmainifest.xml获得许可?
  • @BiploveLamichhane 不,你能帮我吗?
  • 你找到答案了吗?我也面临同样的问题..

标签: flutter dart


【解决方案1】:

在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>

如果还不清楚的话。这是我在debug 目录中的项目中的AndroidMainifest.xml 示例。

<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 clean ....但仍然给出了同样的异常
  • 你添加到调试版本和主版本?
  • 是的,我在两个清单中都添加了所有这些权限:
  • 您能否通过进入应用程序中的设置检查我们是否成功添加权限。
  • 我在我的问题中添加了设置的截图......请看一下。
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2019-11-27
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多