As you have started to see, Flutter offers several options to store data locally. You will now see how to store files locally.
Now, each storage option has its own advantages and drawbacks, so you might wonder: with so many choices, why should you choose to store data into files? Well, there are several reasons and scenarios where files are a good choice to store data:
-
Easy to share & cross platform: Files are easy to share: you can easily send files to other devices, or share them with other apps within your device. In fact files are universal: you can open a text file, an image or an html file almost everywhere.
-
Simple: If your data naturally fits a file model, like audio files, images, or custom file formats, then file storage is a straightforward and effective solution.
-
Effective for large data: when you deal with large amounts of data, like videos, storing them as files can be more efficient than trying to store them in a database.
Of course, there are some drawbacks as well: for example, when you have structured data, a database might be a better solution.
When you deal with files in Flutter, there are two very important packages you should be aware of: path and path_provider.
The path package helps dealing with file paths: for example, it contains methods to retrieve a file directory name or its extension. In our code we’ll use its join method, that
You use the path_provider package to find common locations on the filesystem, and specifically the documents and temp directories, where your app has the permissions to read and write files. Again, this works regardless of the user system: Android, iOS or Desktop. Note that path_provider is currently not available for the web.
Back to our app, let’s add both packages to our project:
Open your Terminal in the project’s directory, and type
flutter pub add path
Let’s repeat this for path_provider
flutter pub add path_provider
OK, let’s see how to use these packages in our app next. In particular, we’ll see how to read and write text files first.