SQLite: What is it and how to use it in Flutter?

These days, you must have heard of Facebook Lite, Messenger Lite, and even PubG Mobile Lite. You see, almost every single app in different industries all have its ‘Lite’ version. But those are quite familiar, right? That’s why today, let’s discover Flutter SQLite.

Flutter SQLite is lightweight yet very powerful. Want to know about it NOW? Let’s get started!

What is SQLite?

It is a software C-language library which offers a RDBMS, or relational database management system. Moreover, SQLite is the most used database engine in the whole world. As a matter of fact, it offers such full features that you may not know yet!

Visit SQLite official site to see all 40 features now!

Do not be misled by the “Lite” in the name 

SQLite official site

Developed in 2000, SQLite has gained popularity globally because it implements a small, fast, high-reliable SQL database engine. The latest version is 3.33.0 in August 2020. To download, just click here.

sqlite logo
SQLite logo

Want to know why it becomes the most well-known database engine? In other words, what are its phenomenal features? Let’s move on to the next part!

Why should use SQLite?

Fast

SQLite can write and read small blobs much (about 30%) faster than using fread() or fwrite(). In addition, it also uses less disk space, which means faster speed.

Easy to use API

In SQLite, there are more than 225 APIs and most of them are optional. However, the core one is extra small, simple and quick to learn, so that it is for both starters and experts.

sqlite api
API plays a vital role in everyday use!

Serverless

SQLite is integrated with the app which has access to the database. Moreover, that app can also read and write from the files that are stored on disk directly

On the other hand, other RDBMS like MySQL, PostgreSQL,… demand a distinct server to operate. This proves how SQLite takes the lead in this criteria. 

Self-contained

To put it another way, SQLite has very few dependencies. Also, because SQLite was developed with ANSI-C, if you want to use it for an app, remember to drop these files and compile with your code:

  • Source code: sqlite3.c
  • Header file: sqlite3.h

Furthermore, it requires very little support from external libraries or operating systems. As a result, SQLite is widely used in multiple platforms – the following features will show you all the details!

Cross-platform

From Android, iOS, Linus to *BSD, Mac, Solaris, VxWorks and Windows, SQLite supports them all and is easy to port to one another system!

sqlite platforms
SQLite support multiple platforms

Read more about: iOS vs Android Development: which platform should you choose

Transaction

SQLite implements ACID – atomic, consistent, isolated and durable transactions. Even if the transactions are interrupted by program crashes, operating system crashes or power failures. 

Zero-configuration

It means SQLite requires no setup or administration. SQLite does NOT use any configuration files. Thus, you don’t need to worry about initial installation and configuration.

zero configuration
SQL just works!

Other SQLite’s unique features

  • It uses dynamic types for tables – values are stored in columns regardless of data type.
  • Also,it allows a single database to access different database files.
  • Moreover, it is capable of creating fast and speedy in-memory databases.

With so many functional features, what can SQLite use for?

What is it for? (suggested)

  • Database of IoT – Internet of Things
  • App file format
  • Cache for enterprise data
  • Websites
  • Data analysis
  • File archive and/or data container
  • Server-side database
  • Data transfer format
  • And many more…

How to use Flutter SQLite?

We highly recommend using Flutter SQLite. Because it is one of the most common ways to store data. Here, we will guide you through 4 ultimate steps in Flutter SQLite:

Step 1: Dependencies

Firstly, go to pubspec.yaml and find dependencies. Then, add the latest version of sqlite and path_provider.

Some use the path_provider package to get locations, a tip that you may find useful.

dependencies:
  flutter:
    sdk: flutter
   sqlite: any
  path_provider: any

Step 2: DB Client

…which is Database.dart. Here, we need to create a singleton:

  • Create a private constructor
  • Setup database 
class DBProvider {
  DBProvider._();
  static final DBProvider db = DBProvider._();
}
static Database _database;

  Future<Database> get database async {
    if (_database != null)
    return _database;

    // if _database is null we instantiate it
    _database = await initDB();
    return _database;
  }

A singleton would ensure the fact that we only have 1 class instance and provide global access to it.  

Step 3: Model Class

This step mainly means to use toMap and fromMap methods to convert the database into Dart Maps.

/// ClientModel.dart
import 'dart:convert';

Client clientFromJson(String str) {
  final jsonData = json.decode(str);
  return Client.fromMap(jsonData);
}

String clientToJson(Client data) {
  final dyn = data.toMap();
  return json.encode(dyn);
}

class Client {
  int id;
  String firstName;
  String lastName;
  bool blocked;

  Client({
    this.id,
    this.firstName,
    this.lastName,
    this.blocked,
  });

  factory Client.fromMap(Map<String, dynamic> json) => new Client(
        id: json["id"],
        firstName: json["first_name"],
        lastName: json["last_name"],
        blocked: json["blocked"] == 1,
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "first_name": firstName,
        "last_name": lastName,
        "blocked": blocked,
      };
}

Step 4: CRUD operations

4.1 Create by using rawInsert and insert
newClient(Client newClient) async {
    final db = await database;
    var res = await db.rawInsert(
      "INSERT Into Client (id,first_name)"
      " VALUES (${newClient.id},${newClient.firstName})");
    return res;
  }

and

newClient(Client newClient) async {
    final db = await database;
    var res = await db.insert("Client", newClient.toMap());
    return res;
  }
4.2 Read

Client by id: use whereArgs

getClient(int id) async {
    final db = await database;
    var res =await  db.query("Client", where: "id = ?", whereArgs: [id]);
    return res.isNotEmpty ? Client.fromMap(res.first) : Null ;
  }

Client with a condition: use rawQuery

getAllClients() async {
    final db = await database;
    var res = await db.query("Client");
    List<Client> list =
        res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
    return list;
  }
4.3 Update an existing Client
updateClient(Client newClient) async {
    final db = await database;
    var res = await db.update("Client", newClient.toMap(),
        where: "id = ?", whereArgs: [newClient.id]);
    return res;
  }
4.4 Delete

1 Client

deleteClient(int id) async {
    final db = await database;
    db.delete("Client", where: "id = ?", whereArgs: [id]);
  }

Every Client

deleteAll() async {
    final db = await database;
    db.rawDelete("Delete * from Client");
  }
4.5 Demo (refactoring to use BLoC Pattern)

That’s all the 4 steps you need to use Flutter SQLite. What to do if you struggle in the middle of the process?

Need help on Flutter SQLite? ACCESS US NOW!

We truly believe that hiring experts is a great investment – a bargain! Founded in 2007, ArrowHiTech JSC is one of the leading IT outsourcing companies in Vietnam. We have worked with over 1,000 customers worldwide and completed more than 10,000 projects. Based in an Asian country, we provide effective services at a very low cost.

We value every customer, treat them like family and build relationships on trust. For that reason, we are confident that we can help YOU operate your online stores and deliver the best solutions at an affordable cost. For reference, check out our Flutter App Development service right now – we welcome customers all the time!

Wrap up

Finally, we have come to the end of today’s article: Flutter SQLite. AHT hopes that you have learned lots of new ideas and methods to use it in Flutter. Again, as usual, we truly wish you the best of good luck and success!

Tags

Share