How to create specific file if it doesnt exist in flutter

Viewed 38

i have a question, i want to open a file using

getPath() async {
  Directory directory = await getApplicationDocumentsDirectory();
  String path = directory.path;
  return path;
}

/.../

var path = await getPath();

File file = ("${path}/data.txt") // if data.txt doesnt exist??

this function. The issue is that, if the file doesnt exist, i get this error: OS Error: The system cannot find the file specified.

So, how can i create that file if it doesnt exist?

Thanks a lot

Edit: Error log:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot open file, path = 'C:\Users\giann\OneDrive\Έγγραφα/data1.txt' (OS Error: The system cannot find the file specified.

, errno = 2)
#0      _File.throwIfError (dart:io/file_impl.dart:635:7)
#1      _File.openSync (dart:io/file_impl.dart:479:5)
#2      _File.readAsBytesSync (dart:io/file_impl.dart:539:18)
#3      _File.readAsStringSync (dart:io/file_impl.dart:584:18)
#4      _File.readAsLinesSync (dart:io/file_impl.dart:590:36)
#5      checkDate (package:example/main.dart:105:16)
#6      _DateRoomSelectRoute.build.<anonymous closure> (package:example/main.dart:191:39)
<asynchronous suspension>
1 Answers

Check if the file exists and if it doesnt you can create it with the create method

bool doesFileExists = await file.exists();
if(!doesFileExists){
  file.create();
}
Related