简体   繁体   中英

Write text to file in Flutter(Dart)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM