Flutter with SQLite
In this story I’m gonna tell you my experience implementing offline database in my Flutter project.
To add SQLite into your app, you need to install sqflite library. It’s a third party library that has SQLite in it.
To install SQFlite, I type into the terminal:
flutter pub add sqflite
Writing that in the terminal is way faster than to search the latest version of sqflite in the pub.dev website and add it to pubspec.yaml
file. In your pubspec.yaml
, a new line that contains sqflite
should be automatically added inside dependencies:
that looks something like this:
Database Helper
The first thing to do is to create a class that can handle the creation and calls to the database. I created report_database_helper.dart
as a singleton so we can access the database anywhere and don’t take up too much memory.
In SQLite, there is no column type that can store a date. If you want to store a date like my monitoring_date
you need to use INTEGER
and convert your date to integer with DateTime.fromMillisecondsSinceEpoch(int)
and from integer with DateTime.millisecondsSinceEpoch
. You can see my example later down below.
This is the Report
class model that I want to store in the database. You can ignore attributes that are List
, because to store list you need a one-to-many relationship in our tables, which is not store in the report table.
Class Helper
Next, I created another helper to that has almost the same methods as ReportDBHelper
, but takes in Report
arguments and outputs, not Map<String, dynamic>
to make it easier to call the functions. I named it ReportHelper
. I also create toMap()
and fromMap()
to convert the Report class to and from a Map.
Usage
Now, all you have to do to store a Report
object into the database is very simple. You just call your methods from ReportHelper
.
Updates
Update #1
I found a better way to create a singleton class, that is with factory
keyword.
The main difference is how you get the instance, which looks cleaner to me.
Update #2
When you want to create relations between tables (for example report
and activity_item
), you need to create the table in the same database file. I know it seems obvious, but it took me too long to realized it :) . To create in the same file, you can execute CREATE TABLE for each of the tables.