So you’ve created a beautiful Flutter app and now you’re wondering how to persist data between app launches. Well, you have a couple of options:
- If you’re storing a small amount of data you can use the shared_preference plugin and save it using key-value pairs.
- If your data structure is not based on few elements but not even large objects you can write and read files to disk using the path_provider package and the dart:io library.
- If your app needs to read and write a large volume of data the best option is to save it in a database using the sqflite package.
In this article we will be focusing on sqflite, which is the SQLite plugin for Flutter (yes the “f” of the name stands for Flutter 😄). SQLite is the most used database engine for mobile application, because it’s reliable, small and fast.
On this example we will create a little database to store TV Series you can’t wait to binge watch (yes, I know you have all the major streaming services subscriptions but 24 hours per day is too little time for using all of them, let’s try not to forget any of them).
The first thing to do is to add the following packages to your
pubspec.yaml file, we will use
path_provider to find the correct path to save the database.
Once you’ve added those up install the packages running a good old
flutter pub get.
Now let’s create our helper class that will manage all the database functions. it is not “essential” to do that in a single class, you can also have initialization and data creation on Widgets or other places, but I’m sure you’ll need a bit of order in your code.
database_manager.dart class with this content.
This is the singleton class that we will use to interact with the database, using
DatabaseManager.instance. We’ve created the singleton and added the code to create the TVSeries table.
Now let’s create the model class that will represent a TV series in our app (
tv_series.dart). Each TV series will have an id, a title, an image, the number of episodes and a description. The functions
toDbMap will be used to save and retrieve
TVSeries objects from the database. See that’s good practice to have these methods on the class.
The last thing that we have to do is to add functions to fetch, add, edit or delete
TVSeries in the
Below you’ll see some useful methods you can integrate on your helper class:
Fetch all TV Series
Add a TV Series
Update a TV Series
Delete a TV Series
Well, you got to the bottom, was it hard? It wasn’t, right?
Be aware that there’s not really a “wrong” method to store data, you can absolutely have thousands of files saved, but SQFLite is not only the most used data persistence method but also the one recommended by Flutter team, so it will mean something… Ain’t it?