我正在尝试创建一个新文件并在 Flutter 中写入它,但收到一条错误,指出: [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FileSystemException: Cannot create file, path = ' /data/user/0/com.micharski.d_ball/app_flutter/levels/level101.json'(操作系统错误:没有这样的文件或目录,errno = 2)
这是我的代码(我正在使用 path_provider 插件):
class LevelFactory {
Level level;
File levelFile;
Future<File> _createLevelFile() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
File file = File('levels/level101.json');
return file.create();
}
Future<void> createLevel() async {
if(level != null){
level = null;
}
levelFile = await _createLevelFile();
print(levelFile);
}
}
Run Code Online (Sandbox Code Playgroud)
驱动程序类内部:
var customLvl = new LevelFactory();
customLvl.createLevel();
Run Code Online (Sandbox Code Playgroud)
出于调试目的,我将其添加到 _createLevelFile() 中:
Directory dir2 = Directory('$appDocPath/levels');
print('DIR2 PATH: ${dir2.absolute}');
Run Code Online (Sandbox Code Playgroud)
我的输出现在是这样的:
I/flutter ( 7990): DIR2 PATH: Directory: '/data/user/0/com.micharski.d_ball/app_flutter/levels'
E/flutter ( 7990): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FileSystemException: Cannot create file, path = '/data/user/0/com.micharski.d_ball/app_flutter/levels/level101.json' (OS Error: No such file or directory, errno = 2)
Run Code Online (Sandbox Code Playgroud)
Flutter 中的文件路径不能是相对的。移动操作系统会将路径解释为"levels/level101.json"无效路径或指向您的应用无权访问的位置的路径。您需要使用一个插件path_provider来获取应用程序的本地数据文件夹的路径,然后从中构建绝对路径。
import 'package:path_provider/path_provider.dart';
Future<File> _createLevelFile() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
File file = File('$appDocPath/levels/level101.json');
return await file.create();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8299 次 |
| 最近记录: |