Flutter报错OS Error: No such file or directory errno=2 仅tech_tree_repository触发求助
问题根因
你当前报错的核心原因是:getApplicationDocumentsDirectory()指向的是App运行时的私有沙盒文档目录,并非项目里的assets静态资源目录。map_repository能正常运行,是因为你之前有提前将map_data.json写入到沙盒目录的逻辑,而三个种族的科技树json文件没有执行过写入沙盒的操作,直接用File类读取自然找不到文件。
另外你代码中await json.decode(file.readAsStringSync())的写法存在错误:readAsStringSync是同步IO方法,json.decode也是同步方法,加await没有任何意义,还可能引发逻辑异常。
修复方案
根据你的使用场景二选一即可:
场景1:读取项目assets中的静态科技树配置
如果你的科技树json是不会动态修改的静态资源,直接替换读取逻辑即可:
- 首先确认
pubspec.yaml中已经正确配置了科技树json的assets路径 - 导入Flutter服务包:
import 'package:flutter/services.dart'; - 替换tech_tree_repository中原有的文件读取逻辑:
// 删掉原有的Directory、File相关的读取代码 if (selectedTribe == "terran") { String techStr = await rootBundle.loadString("assets/terran_tech_tree.json"); techTreeContents = json.decode(techStr); } else if (selectedTribe == "protoss") { String techStr = await rootBundle.loadString("assets/protoss_tech_tree.json"); techTreeContents = json.decode(techStr); } else { String techStr = await rootBundle.loadString("assets/zerg_tech_tree.json"); techTreeContents = json.decode(techStr); }
场景2:读取沙盒中可动态修改的科技树配置
如果你的科技树json会在运行时修改后持久化存储,需要先把assets中的初始文件复制到沙盒目录:
- 新增初始化方法,在App启动或第一次调用科技树逻辑前执行:
Future<void> initTechTreeFile() async { final dir = await getApplicationDocumentsDirectory(); const fileNames = [ "terran_tech_tree.json", "protoss_tech_tree.json", "zerg_tech_tree.json" ]; for (var name in fileNames) { final targetFile = File("${dir.path}/$name"); if (!await targetFile.exists()) { String content = await rootBundle.loadString("assets/$name"); await targetFile.writeAsString(content); } } }
- 初始化完成后再执行你原有读取逻辑即可,同时建议把同步读方法换成异步读:
// 原if分支内修改为 file = File("${directory.path}/terran_tech_tree.json"); String fileContent = await file.readAsString(); techTreeContents = json.decode(fileContent);
优化建议
- 读取文件前先调用
await file.exists()做存在性判断,避免直接抛出异常 - 取
selectedtechTreeList[0]前先判断列表是否为空,避免范围越界错误
内容的提问来源于stack exchange,提问作者97_HYUN
相关产品推荐
相关产品推荐

