【问题标题】:flutter get files code not working on android 12flutter 获取文件代码在 android 12 上不起作用
【发布时间】:2022-12-20 10:52:53
【问题描述】:

我想阅读并获取不同的文件,如 mp3、pdf 和 jpg。并且工作正常但在 android 12 上列表文件不起作用这是获取文件的代码

 void getFiles() async {
if ( await Permission.manageExternalStorage.request().isGranted) {
  // Either the permission was already granted before or the user just granted it.
}
//asyn function to get list of files
List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
var root = storageInfo[0]
    .rootDir; //storageInfo[1] for SD card, geting the root directory
var fm = FileManager(root: Directory(root)); //
files = await fm.filesTree(
    excludedPaths: ["/storage/emulated/0/ssssssssssss"],
    extensions: ["jpg"] //optional, to filter files, list only pdf files
    );

setState(() {}); //update the UI

}

【问题讨论】:

    标签: flutter dart flutter-dependencies flutter-test


    【解决方案1】:

    您的代码的问题似乎是您使用的是 PathProviderEx 包,Android 12 不支持该包。PathProviderEx 包使用已弃用的 MediaStore API,Android 12 不再支持该 API。

    要解决此问题,您可以改用 path_provider 包,它使用新的 MediaStore API。以下是如何修改代码以使用 path_provider 包的示例:

    import 'package:path_provider/path_provider.dart';
    
    void getFiles() async {
      if (await Permission.manageExternalStorage.request().isGranted) {
        // Either the permission was already granted before or the user just granted it.
      }
    
      // Get the root directory for the primary storage
      var root = (await getExternalStorageDirectory()).path;
    
      // Create a FileManager instance
      var fm = FileManager(root: Directory(root));
    
      // Get the list of files in the root directory
      files = await fm.filesTree(
        excludedPaths: ["/storage/emulated/0/ssssssssssss"],
        extensions: ["jpg"] // optional, to filter files, list only jpg files
      );
    
      setState(() {}); // update the UI
    }
    

    在这段代码中,path_provider 包用于获取主存储的根目录,FileManager 类用于列出根目录中的文件。 filesTree 方法用于获取文件列表,extensions 参数用于过滤结果以仅包含具有指定扩展名的文件(在本例中,仅包含 jpg 文件)。

    请注意,这只是一个示例,您可能需要根据您的具体要求和应用程序的详细信息修改代码。

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2022-11-18
      • 1970-01-01
      • 2022-07-20
      • 2020-12-05
      • 2019-06-30
      • 2019-07-30
      • 2019-10-17
      • 2020-06-27
      相关资源
      最近更新 更多