Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Data Persistence with SQLite | Flutter

Whenever you need to store the data on the local then you need to use SQLite to persist the user data.

Why we use SQLite?

SQLite is a popular choice as embedded database software for local/client storage in application software such as web browsers.

How to use SQLite in a flutter?

Before using SQLite, you should know that

SQLite is not available in a flutter SDK like Android but we have a plugin sqflite that exactly performs all the operation on the database just like in Android and iOS.

Flutter plugin is the wrapper of the native code written in Kotlin or java for Android and swift or objective-c for iOS.
P.S : Plugin can also be created only with dart code

If you are new to SQLite, go through SQLite Tutorial site below

SQLite Tutorial – An Easy Way to Master SQLite Fast
This SQLite tutorial teaches you everything you need to know to start using SQLite effectively. You will learn SQLite…www.sqlitetutorial.net

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file .

  sqflite:
path_provider:

To work with SQLite databases, import the sqflite and path packages

  • The sqflite package provides classes and functions that allow you to interact with a SQLite database.
  • The path_provider package provides functions that allow you to correctly define the location to store the database on disk such as TemporaryDirectory and ApplicationDocumentsDirectory.

Step 2: Create a Model class

SQLite creates a table for the model class, the fields in the class correspond to columns in the table. Therefore, the classes tend to be small model classes that don’t contain any logic. Our Person class represents the model for the data in the database.

class Person {
int id;
String name;
String city;

Person({this.id, this.name, this.city});

}

If we want to insert into the database then we need to convert the Person into a Map

Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"city": city,
};

and if we want to retrieve from the database then we need to convert the Map into the Person

factory Person.fromMap(Map<String, dynamic> json) => new Person(
id: json["id"],
name: json["name"],
city: json["city"],
);

This is how our PODO class will look like

https://gist.github.com/ashishrawat2911/d74ea7944b53f193832793c1fe5f54a9#file-person-dart

Step 3: Create a database

We will make a separate class as database.dart to make the code more modular and add all the requirements meths for managing the database that can be accessed anywhere in the app.

Create a class DatabaseProvider

class PersonDatabaseProvider{
DatabaseProvider._();

static final PersonDatabaseProvider db = PersonDatabaseProvider._();
}

Step 4: Open the Database

Before you read and write data to the database, you need to open a connection to the database. This involves two steps:

  1. Define the path to the database file using the getDatabasesPath from the sqflite package combined with the pathfunction from the path package
  2. Open the database with the openDatabase function from sqflite
Directory directory = await getApplicationDocumentsDirectory();

String path = join(directory.path, "person.db");

final Future<Database> database = openDatabase(path);

Step 5: Create the table

you need to create a table to store information. 
For example, In our case, we create a table called Person that defines the data that can be stored. In this case, each Person contains an id, name, and city. Therefore, these will be represented as three columns in the Person table.

  1. The id is a Dart int, and will be stored as an INTEGER SQLite Datatype. It is also good practice to use an id as the primary key for the table to improve query and update times.
  2. The name is a Dart String, and will be stored as a TEXT SQLite Datatype
  3. The city is also a Dart String, and will be stored as an TEXT Datatype

To prevent from opening a connection to the database again and again we can use this:

https://gist.github.com/ashishrawat2911/a59ab9ece9649d1de3dc9527b870c99b#file-createdatabase-dart

Step 6: Managing the data

Now we are going to show you how you can perform an operation on the SQLite database.

Query:

https://gist.github.com/ashishrawat2911/333a6b650568b9b59468a2e70e33175b#file-query-dart

getAllPersons() will return all the person from the SQLite database if available.

Insert:

https://gist.github.com/ashishrawat2911/2ed7bcdf77d253d4940bcf0681afbc6d#file-insert-dart

Delete:

https://gist.github.com/ashishrawat2911/5969e225083a5c8ff995618fdab95a01#file-delete-dart

If you see we have two methods, one deletes the row with particular id and other deletes all data present in the table, you can change all the query according to your need.

Update:

https://gist.github.com/ashishrawat2911/f25acd6599b120bfa3e1d68a58b4430d#file-update-dart

If these small code snippets still confuse you we have the complete code of the database class:

https://gist.github.com/ashishrawat2911/16c4d20501f8bec519b914ee6e49480d#file-database-dart

Step 7: Using the data

In order to use the database we need to create the instance of the database and use the method present in the database class

DatabaseProvider.db

This will help us to perform an operation on the database.

like if we want to get the person in the database we will use the method that we have defined in our DatabaseProvider class

DatabaseProvider.db.getAllPersons()

and if I want to display it in the list then I’ll use FututeBuilder :

https://gist.github.com/ashishrawat2911/fdf814c9638976a57d440329a318257f#file-bodysql-dart


we have also linked a repo if you need to see the example of SQLite.

ashishrawat2911/flutter_sqlite
Contribute to ashishrawat2911/flutter_sqlite development by creating an account on GitHub.github.com

That it for SQLite in flutter.

Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Connect with me on Linkedin and Github


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.