Search code examples
flutterpathprovidercreatefile

Flutter create a file and write its contents


I am working on an app which gathers text content from server and as the next step I am trying to save them into separate files to be saved with in apps storage. Storage is a folder called 'storage'. Inside storage, there is a 'fileList.txt' file which contains the list of files.

In pubspec.yaml I declared this folder in the assets as follows:

 assets:
- storage/

And I can read it using the following function:

Future<String> readFileContent() async {
    String response;
    response =
        await rootBundle.loadString('storage/fileList.txt');
    return response;
  }

To save the file I made use of online examples which use 'path_provider' package. However when I try to save one of the downloaded files for instance 'file4.dat' using the following functions, I encounter the following error. How can I resolve that problem?

  saveFileLocally() async {
    await _writeFile();
  }
  
  Future<Null> _writeFile() async {
    await (await _getLocalFile()).writeAsString(vars.fileContents);
  }

  Future<File> _getLocalFile() async {
    // get the path to the document directory.
    String dir = (await PathProvider.getApplicationSupportDirectory()).path;
    print('DIR :::: ' + dir);
    return new File(
        '$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
  }

The error is:

Unhandled Exception: FileSystemException: Cannot open file, 
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)

Thanks guys and take care !!! :)


Solution

  • While checking out path_provider examples, I ran into this important detail:

    Directory directory = Platform.isAndroid
            ? await getExternalStorageDirectory() //FOR ANDROID
            : await getApplicationSupportDirectory(); //FOR iOS
    

    This solved my problem. I am no longer using default rootBundle asset to process any external files.