Flutter Reading and Writing Files:
We already know that, to read and write files to disk. This can be used to persist data across app launches and some times we are downloading data from the internet and saved it in our laptop/any external device to use it for later offline use when the internet is not available.
Adding Dependency package into your package’s pubspec.yaml file:
Add the below code into pubspec.yaml file
dependencies:
path_provider:
Note: After adding this package run get package method to add all dependencies into it
If you don’t add this dependency package it will show package not found an exception in your main.dart file
Follow the below steps to Read and Write Files in Flutter:
- Finding the correct local path
- Create a reference to the file location
- Write data to the file
- Read data from the file
Finding the correct local path:
Now in this example, we are going to display a counter. When the counter changes, we want to write data on disk so when the app loads we can read it again.
To access commonly used locations on the device’s file system The path_provider
plugin provides a platform-agnostic way. The plugin currently supports access to two file system locations :
- Temporary directory: A temporary directory is a (cache) that the system can clear at any time. On iOS, it will be
NSTemporaryDirectory
()
returns. On Android, we will get this value thatgetCacheDir()
returns.
- Documents directory: To store a new app we use a directory for the app to store files that only it can access. The system clears the directory only when the app is deleted. On iOS, this is the directory name
NSDocumentDirectory
. On Android, it will beAppData
directory.
In this example, we are storing information in the documents directory. We have to find the path to the documents directory :