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.

In this Tutorial Article, We will demonstrate how to use SQLite in Flutter for creating Mobile Applications.

Why SQLite?

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. Under 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.
https://medium.com/media/edea770ec7b04b17504c8c1f45a9605a

NOTE: Sqflite flutter package

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 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 TestDB and 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 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:https://medium.com/media/005feef23a1e9d2f47713919547a44fa


4. CRUD operations

CREATE:

The SQFlite flutter 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 :https://medium.com/media/6b63258f258159d39eac93ec436433d1



Using insert :https://medium.com/media/df0408b3055852ed1478bbccd5cc2471



Another example using the biggest ID as a new ID:https://medium.com/media/ea48787b5d3b8e41b42a1706610dd950

READ:

Get Client by id
https://medium.com/media/2a276f0c73b38c6a5e027abac5869ada



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:https://medium.com/media/9901f8807075a406e06958965a083a61



Example: Only get the Blocked Clientshttps://medium.com/media/6a0b2945d70d7eb64570977bf15dfab5

UPDATE:

Update an existing Client

https://medium.com/media/039e90e7b0bdb9ee2f830f0a7a0ee9d9

Example: Block or unblock a Client:https://medium.com/media/6877d6826814e5f8622e4a38031af589

DELETE:

Delete one Client
https://medium.com/media/13c7c1abe0bd28a46330b90e1ece5223

Delete All Clients

https://medium.com/media/744fe224c20f26a1cea933d590981067

You Might Also Like : Chat App in Flutter with Firebase


DEMO:

Image for post

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

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.https://medium.com/media/748c6b6a752a4f8ffdd267b3ae07f728

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:https://medium.com/media/282de05ea195a5457108bd03a04a687a

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.
Image for post

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 :

https://medium.com/media/2c23446ee6dd81595d86e8a766bef4cb
NOTES: 

  1. 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 in SQLite.
  2. 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.
  3. 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 :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.

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.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

Image for post

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 ). 

© medium