31. Data persistence with SQLite in Flutter

Página 254

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:

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.

Next page of the Free Ebook:

25531.1. Data Persistence with SQLite in Flutter: Introduction to SQLite

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text