Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a new text file in Flutter

Tags:

io

flutter

dart

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)
like image 317
code writer 3000 Avatar asked Oct 22 '25 06:10

code writer 3000


1 Answers

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();
}
like image 115
Abion47 Avatar answered Oct 25 '25 09:10

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!