Using SQLite in Flutter
Persisting data is very important for users since it would be inconvenient for them to type their information every time or wait for the network to load the same data again. In situations like this, it would be better to save their data locally.
In this article, I will demonstrate this using SQLite
in Flutter.
If you speak portuguese you can find the translated version here
Why SQLite?
SQLite is one of the most popular ways to store data locally. For this article, we will be using the package sqflite
to connect with SQLite. Sqflite is one of the most used and up to date packages for connecting to SQLite databases in Flutter.
1. Add dependencies to your project
In your project go to pubspec.yaml
and look for dependencies
. Under dependencies
, add the latest version of sqflite
and path_provider
(use the right numbers from Pub).
NOTE:
We use the path_provider
package to get the commonly used location such as TemporaryDirectory
and ApplicationDocumentsDirectory
.
2. Create a DB Client
Now in your project create a new file Database.dart
. In the newly created file, we need to create a singleton.
Why we need singleton: We use the singleton pattern to ensure that we have only one class instance and provide a global point access to it
1.Create a private constructor that can be used only inside the class :
2.Setup the database
Next we will create the database object and provide it with a getter where we will instantiate the database if it’s not (lazy initialization).
If there is no object assigned to the database, we use the initDB
function to create the database. In this function, we will get the path for storing the database and create the desired tables:
NOTE: The database name is
TestDB
and the only table we have is calledClient
. If you don't know what's going on you really need to go and learn some SQL it's more important than water.
3. Create the Model Class
The data inside your database will be converted into Dart Maps so first, we need to create the model classes with toMap
and fromMap
methods. I am not going to cover how to do this manually. If you don’t know how to do this, you should consider reading this article by Poojã Bhaumik.
To create our model classes, I am going to use this website. If you don’t already have it bookmarked, you really should :)
You can click here to see how it all works
Our Model:
4. CRUD operations
Create
The SQFlite
package provides two ways to handle these operations using RawSQL
queries or by using table name and a map which contains the data :
Using rawInsert
:
Using insert
:
Another example using the biggest ID as a new ID:
Read
Get Client by id
In the above code, we provide the query with an id
as the argument using whereArgs
. We then return the first result if the list is not empty else we return null.
Get all Clients with a condition
In this example I used rawQuery
and I mapped the result list to a list of Client
objects:
Example: Only get the Blocked Clients
Update
Update an existing Client
Example: Block or unblock a Client:
Delete
Delete one Client
Delete All Clients
Demo
For our demo, we will create a simple Flutter app to interact with our database.
We will first start with the app’s layout:
Notes :
1. The FutureBuilder
is used to get the data from the database.
2. The FAB to adds a random client to the database when it’s clicked.
3. A CircularProgressIndicator
is shown if there is no data.
4. When the user clicks the checkbox the client will be blocked or unblocked according to the current state.
Now it’s very easy to add new features, for example, if you want to delete a client when the item is swiped, just wrap ListTile
with a Dismissible
Widget like this:
For our OnDismissed
function, we are using the Database provider to call the deleteClient
method. For the argument, we are passing the item’s id.
Refactoring to use BLoC Pattern
We have done a lot in this article but in real world application, making state part of the UI isn’t really a good thing. Instead, we should always keep them separated.
There are a lot of patterns for managing state in Flutter but I will use BLoC in this article because it’s very flexible.
Create the BLoC :
Notes :
getClients
will get the data from the Database (Client table) asynchronously. We will call this method whenever we update the table hence the reason for placing it into the constructor’s body- We
StreamController<T>.broadcast
constructor so that we are able to listen to the stream more than once. In our example, it doesn't make much of a difference since we are only listening to the stream once but it is good to consider cases where you want to listen to the stream more than once. - Don't forget to close your stream. This prevents us from getting memory leaks. In our example, we will close it using the dispose method of our
StatefulWidget
.
Now let’s add some methods to our block to interact with the database :
And that’s all for our BLoC!
Our next step would be finding a way to provide our bloc to our widgets. We need a way to make the bloc accessible from different parts of the tree while also being able to free itself from memory when not in use.
For this, can take a look at this library by Remi Rousselet .
In our case, the bloc is only going to be used by one widget so we can declare it and dispose of it from our stateful widget.
Next, we need to use StreamBuilder
instead of FutureBuilder
. This is because we are now listening to a stream (clients
stream) instead of a future.
The final step would be to refactor our code so that we are calling the methods from our bloc and not the database directly:
Here is the final result
Finally, you can find the code source for this example in this repo (check the sqlite_demo_bloc branch to see the new version after refactoring ). I hope you enjoyed this article.