0
votes

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)
1

1 Answers

0
votes

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();
}