So don’t know how to Use SQLite in Flutter? don’t worry we got your back. We will be using sqflite flutter package to store SQLite database 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. Thus we use SQLite in flutter.
SQLite is one of the most popular ways to store data locally. For this article, we will be using the package Sqflite in flutter to connect with SQLite in flutter. Sqflite is one of the most used and up to date packages for connecting to SQLite database in Flutter.
1. Add dependencies to your project
In your project go to
pubspec.yaml and look for
dependencies, add the latest version of Sqflite flutter package and
path_provider (use the right numbers from Pub). To get data via SQLite in Flutter.
NOTE: Sqflite flutter package
We use the
path_provider package to get the commonly used location such as
2. Create a DB Client
Now in your SQLite in Flutter 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 :https://medium.com/media/b971bdd94aee46637afdbd5da4018129
2. Setup the SQLite database in Flutter.
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).https://medium.com/media/34adfafdd24d53d6b906b1bf0f0ddf96
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:https://medium.com/media/b8661b9ea147182d2680205c42335b8c
NOTE: The database name is
TestDBand the only table we have is called
Client. 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
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 🙂
4. CRUD operations
SQFlite flutter packageprovides two ways to handle these operations using
RawSQLqueries or by using table name and a map which contains the data :
Another example using the biggest ID as a new ID:https://medium.com/media/ea48787b5d3b8e41b42a1706610dd950
Get Client by id
In the above code, we provide the query with an
idas 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
rawQueryand I mapped the result list to a list of
Example: Only get the Blocked Clientshttps://medium.com/media/6a0b2945d70d7eb64570977bf15dfab5
Update an existing Client
Example: Block or unblock a Client:https://medium.com/media/6877d6826814e5f8622e4a38031af589
Delete one Client
Delete All Clients
You Might Also Like : Chat App in Flutter with Firebase
For our demo, we will create a simple Flutter app to interact with our database.
We will first start with the app’s layout:https://medium.com/media/d2aef12770bc215f48760c615866fbea
FutureBuilderis used to get the data from the database.
2. The FAB to adds a random client to the database when it’s clicked.https://medium.com/media/748c6b6a752a4f8ffdd267b3ae07f728
CircularProgressIndicatoris 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
DismissibleWidget like this:https://medium.com/media/282de05ea195a5457108bd03a04a687a
OnDismissedfunction, we are using the Database provider to call the
deleteClientmethod. 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 for the creation of SQLite database in Flutter.
Create the BLoC :
getClientswill 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 in SQLite.
StreamController<T>.broadcastconstructor 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
Now let’s add some methods to our block to interact with the database :https://medium.com/media/5a76e5430b0805520b024b055f1c73de
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.
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.https://medium.com/media/ea8bd1949c4bde3fae8e249cd6a7a249
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.https://medium.com/media/9570fd49476a9726131aa6cc1d5788fd
The final step would be to refactor our code so that we are calling the methods from our bloc and not the database directly:https://medium.com/media/3a48e31975b6f965b131ead5bdfd04d4
Here is the final result