Flutter Read/Write File Example – with path_provider and dart:io

In this tutorial, we’re gonna build a Flutter App that can read file and write data to file for later use. To do this, we need to combine path_provider plugin with dart:io library.

Flutter App Overview

Our Flutter App has a Text field, when we click on Write to File button, the String in Text field will be written to text.txt file (appending text) and display on Screen.

flutter-read-write-file-example-overview

Everytime we launch the App, it read text.txt file and show contents inside.
We can also clear content of the file by Clear Contents button.

Read/Write Files

Find Local Path

We need a place to write data on disk and read it again when the app loads.
>> So we use path_provider plugin to access Documents directory (on iOS, this corresponds to NSDocumentDirectory, on Android, this is the AppData directory).

Reference to File

To create a reference to the File full location (in our case, the text.txt file), we use File class from the dart:io library.

Write data to File

We will write a string to a file using File writeAsString() method. It returns a Future<File> that completes with this File object once the entire operation has completed.

By default, writeAsString() creates the file and truncates the file if it already exists.
>> To append data to existing file, we pass FileMode.append mode as second parameter.

Read data from File

We use File readAsString() method to read the entire contents as a string. It returns a Future<String> that completes with the string once contents has been read.

Complete Code

Source Code

file_example

By grokonez | July 13, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*