Data persistence with SQLite in Flutter

Capítulo 254

Estimated reading time: 4 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

Data persistence is a crucial aspect of application development. In Flutter, one of the most common ways to persist data is using SQLite, a built-in SQL database engine. In this chapter, let's explore how you can integrate SQLite into your Flutter application to persist data.

What is SQLite?

SQLite is an SQL database engine that allows you to store data in a local file on the user's device. It's lightweight, serverless, and doesn't require a separate setup. SQLite is ideal for storing simple data and is widely used on mobile devices and web browsers.

Why use SQLite in Flutter?

Flutter is a mobile app development framework that lets you build native apps with a single code base. However, Flutter doesn't provide a built-in way to persist data. So we need to use third party packages like SQLite for this purpose.

How to use SQLite in Flutter

To start using SQLite in Flutter, we first need to add the dependency to our 'pubspec.yaml' file:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^1.3.2+1

Next, we import the sqflite package into our Dart file:

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app

import 'package:sqflite/sqflite.dart';

With the dependency installed and imported, we can start using SQLite. First, we need to open a database. We can do this using the openDatabase function:

final Future database = openDatabase(
  // Specify the path to the database
  join(await getDatabasesPath(), 'my_database.db'),
);

This function creates a database if it doesn't exist and opens it if it does. The getDatabasesPath() function gets the path to the directory where the application can store the user's private data.

Creating tables

Once the database is open, we can create tables in it. For that, we can use the onCreate function that is called when the database is created for the first time:

final Future database = openDatabase(
  join(await getDatabasesPath(), 'my_database.db'),
  onCreate: (db, version) {
    return db.execute(
      "CREATE TABLE my_table(id INTEGER PRIMARY KEY, name TEXT)",
    );
  },
  version: 1,
);

CRUD Operations

With the database and tables created, we can perform CRUD (Create, Read, Update, Delete) operations.

To insert data, we use the insert function:

Future insertData(MyData data) async {
  final Database db = await database;

  await db.insert(
    'my_table',
    data.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

To read data, we use the query function:

Future> getData() async {
  final Database db = await database;

  final List> maps = await db.query('my_table');

  return List.generate(maps.length, (i) {
    return MyData(
      id: maps[i]['id'],
      name: maps[i]['name'],
    );
  });
}

To update data, we use the update function:

Future updateData(MyData data) async {
  final db = await database;

  await db.update(
    'my_table',
    data.toMap(),
    where: "id = ?",
    whereArgs: [data.id],
  );
}

To delete data, we use the delete function:

Future deleteData(int id) async {
  final db = await database;

  await db.delete(
    'my_table',
    where: "id = ?",
    whereArgs: [id],
  );
}

In summary, SQLite is an excellent choice for data persistence in Flutter applications. It provides an easy way to store data locally on the user's device, making your app more responsive and less dependent on a constant network connection. With the help of the sqflite package, we can perform all the necessary database operations easily and effectively.

Now answer the exercise about the content:

_What is the role of SQLite in Flutter application development?

You are right! Congratulations, now go to the next page

You missed! Try again.

The role of SQLite in Flutter application development is to persist data. SQLite is a database engine that allows storing data locally on the user’s device, which is essential for data persistence in Flutter apps.

Next chapter

Data Persistence with SQLite in Flutter: Introduction to SQLite

Arrow Right Icon
Free Ebook cover How to create apps from scratch to advanced using Flutter and Dart complete course
95%

How to create apps from scratch to advanced using Flutter and Dart complete course

5

(4)

267 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.