You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 08:06:04