Flutter Android端使用file_picker_cross打开文件报错解决方案
Flutter file_picker_cross跨平台文件选择Android端报错问题
开发背景
我正在开发一款Flutter跨平台应用,需要将应用数据加载、存储到设备公共存储区域,以支持文件共享或第三方拷贝,应用兼容目标为Linux、Android平台,优先支持Web端。
技术选型上我使用file_picker_cross库实现文件加载、保存功能,当前文件加载逻辑代码如下:
IconButton(onPressed: () async { FilePickerCross? value = await FilePickerCross.importFromStorage( type: FileTypeCross.any, // 可选值: `any`, `audio`, `image`, `video`, `custom`,注意FDE环境下不支持any类型 fileExtension: '.exam' // 仅FileTypeCross.custom类型下生效,可传入多个后缀如`dot`, `ppt,pptx,odp` ).onError((error, _) { String _exceptionData = error.toString() ; print('---------------------- FilePicker error : $error ${error.runtimeType}'); print('REASON: ${_exceptionData}'); if (_exceptionData == 'read_external_storage_denied') { print('Permission was denied'); } else if (_exceptionData == 'selection_canceled') { print('User canceled operation'); } print('----------------------'); throw Exception("filecros eror"); }); String fileContent = String.fromCharCodes(value.toUint8List()); ref.read(examenProvider.notifier).fromJson(fileContent, ref.read(examineeProvider.notifier),fullProg: ref.watch(nodeProvider), settings: ref.read(nodeProvider.notifier).settings.loaded); candidates = ref.watch(examineeProvider); }, icon: Icon(Icons.file_upload))
已验证现象
- Linux平台下上述代码运行正常,可正常唤起文件选择对话框并返回选中文件
- 库默认返回
Uint8List格式的文件内容,使用库自带自动字符串解码逻辑时,遇到UTF字符会出现解析失败,因此我手动通过String.fromCharCodes(value.toUint8List())获取文件内容字符串 - 按照库官方文档说明,Android端无需额外配置即可运行,但实际Android端运行直接报错,错误日志如下:
---------------------- FilePicker error : type '_Exception' is not a subtype of type 'String' _TypeError I/flutter (22870): REASON: type '_Exception' is not a subtype of type 'String' I/flutter (22870): ---------------------- E/flutter (22870): [ERROR:flutter/runtime/dart_vm_initializer.cc(39)] Unhandled Exception: Exception: filecros eror E/flutter (22870): #0 ExamConfigurator.build.<anonymous closure>.<anonymous closure> (package:examen_helper/exam_configurator.dart:132:25) E/flutter (22870): #1 FutureExtensions.onError.<anonymous closure> (dart:async/future.dart:1012:24) E/flutter (22870): #2 _RootZone.runBinary (dart:async/zone.dart:1690:54) E/flutter (22870): #3 _FutureListener.handleError (dart:async/future_impl.dart:162:22) E/flutter (22870): #4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47) E/flutter (22870): #5 Future._propagateToListeners (dart:async/future_impl.dart:799:13) E/flutter (22870): #6 Future._completeError (dart:async/future_impl.dart:574:5) E/flutter (22870): #7 _completeOnAsyncError (dart:async-patch/async_patch.dart:287:13) E/flutter (22870): #8 FilePickerCross.importFromStorage (package:file_picker_cross/file_picker_cross.dart) E/flutter (22870): <asynchronous suspension>
待解决疑问
- 当前我未修改Android Manifest配置文件,想确认
file_picker_cross是否会自动处理存储权限? - 现有报错信息未明确说明失败原因,是否需要在Manifest中添加文件读写权限?
- 项目使用Riverpod做状态管理,集成
permission_handler的方案改造成本较高,希望获得对应的问题排查思路和解决建议。
内容的提问来源于stack exchange,提问作者bboett
相关产品推荐
相关产品推荐

