Trying to create a new text file in Flutter
File paths in Flutter can't be relative. The mobile operating system will interpret paths like "levels/level101.json"
as either an invalid path or a path to a location that your app doesn't have permission to access. You need to use a plugin like path_provider
to get the path to your app's local data folder and then build absolute paths from that.
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();
}
amicharski
I'm still trying to figure out where to get my head into in the tech industry.
Updated on November 28, 2022Comments
-
amicharski over 1 year
I am trying to create a new file and write to it in Flutter and I get an error that states: [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)
Here is my code (I am using the path_provider plugin):
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); } }
Inside the driver class:
var customLvl = new LevelFactory(); customLvl.createLevel();
For debugging purposes, I added this to _createLevelFile():
Directory dir2 = Directory('$appDocPath/levels'); print('DIR2 PATH: ${dir2.absolute}');
My output is now this:
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)
-
amicharski about 3 yearsI still get the same exception.
-
Abion47 about 3 years@amicharski Does the
levels
directory exist? If not, you'll need to create that first. -
amicharski about 3 yearsYes, and I made changes to the question because I made some adjustments to my code.
-
Abion47 about 3 years@amicharski Have you actually created the directory? The code you added to your question doesn't create the directory, only a
Directory
object. You need to callDirectory.create
to create the directory itself. -
amicharski about 3 yearsthe /levels/ directory was created manually in the file system interface.