升级Android 11后Flutter无法在应用支持目录创建文件夹如何解决?
错误原因
报错是因为Dart中Directory.create()默认不递归创建父目录。你要创建的downloads/literature和downloads/audioLectures路径中,父级目录downloads在应用首次安装时不存在,直接创建子目录就会触发「找不到文件或目录」的系统错误。
修复方案
只需要给create()方法传入recursive: true参数即可,该参数会自动创建路径中所有不存在的父级目录,且目录已存在时也不会抛出异常,所以你原本的exists()判断逻辑也可以省略,简化代码逻辑。
修改后的完整代码如下:
Future<void> main() async { // 异步main方法需要先初始化Widgets绑定 WidgetsFlutterBinding.ensureInitialized(); Directory directory = await getApplicationSupportDirectory(); // 递归创建所需目录,不需要提前判断是否存在 Directory literatureDirectory = Directory("${directory.path}/downloads/literature"); await literatureDirectory.create(recursive: true); Directory audioLecturesDirectory = Directory("${directory.path}/downloads/audioLectures"); await audioLecturesDirectory.create(recursive: true); runApp(ULTApp()); }
recursive: true的行为完全匹配你的需求:不存在则创建全路径目录,已存在则跳过无操作,不需要额外做存在性校验,还能减少一次异步IO查询的耗时。
内容的提问来源于stack exchange,提问作者flutternoob
相关产品推荐
相关产品推荐

