[SOLVED] How to create specific file if it doesnt exist in flutter

Issue

This Content is from Stack Overflow. Question asked by Giannis Petsis

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



Solution

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


This Question was asked in StackOverflow by Giannis Petsis and Answered by Ozan Taskiran It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?