Home > front end >  Write text to file in Flutter(Dart)
Write text to file in Flutter(Dart)

Time:01-18

I want to be able to create a new file and write a string into it. Examples that I can find all seems to pertain to writing to an existing file.

String fileName = 'myFile.txt';
String contents = 'hello';
void writeToFile(String fileName, String contents){
    File outFile = File('content://com.android.providers.media.documents/document/document/document_root/'   fileName);
    outFile.writeAsString(contents);
  }

This results in the following error, as expected

Unhandled Exception: FileSystemException: Cannot open file, path = 'content://com.android.providers.media.documents/document/document/document_root/myFile.txt' (OS Error: No such file or directory, errno = 2)

How can I create a new file in which I can write my contents?

CodePudding user response:

Are you sure that the path exists? writeAsString does create the file if it doesn't exists, but it doesn't create the full folder structure up to the file you're trying to write to. Also, you might not have the rights to write in the path you've specified.

Anyway, you'd better use this plugin to get the folders' path instead of hard-coding them.

  •  Tags:  
  • Related