An essential part of application development is data management. In many applications, it is necessary to store information persistently so that it can be accessed even after the application is restarted or the device is turned off. Here, we are going to discuss how to work with local databases in Flutter using Dart.

SQLite in Flutter

SQLite is a C library that provides a lightweight, disk-based database that does not require a separate server process and allows you to access the database using a non-standard variant of SQL. In Flutter, we use the sqflite library to handle SQLite.

Installation

To begin with, we need to add the sqflite dependency to our pubspec.yaml file. We'll also add the provider path, which we'll use to find the path to the database directory.

dependencies:
  flutter:
    sdk: flutter
  sqflite: any
  path_provider: any

Run the 'flutter packages get' command to install the dependencies.

Opening a database

We can open the database using the openDatabase method. If the database does not exist, it will be created. Here is an example of how to open a database:

import 'package:sqflite/sqflite.dart';

void openDatabase() async {
  final database = await openDatabase(
    join(await getDatabasesPath(), 'doggie_database.db'),
  );
}

Creating tables

After opening the database, we can create tables in it. The onCreate method is called when the database is first created.

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

Insertion of data

We can insert data into our table using the insert method. This method automatically saves the data in a format that SQLite can understand.

Future insertDog(Dog dog) async {
  final db = await database;

  await db.insert(
    'dogs',
    dog.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

Data query

We can query the data in our database using the query method. This method returns a list of maps, where each map is a record in the database.

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

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

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

Data update

We can update the data in our database using the update method. This method takes a map of values ​​to update.

Future updateDog(Dog dog) async {
  final db = await database;

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

Data deletion

We can delete data from our database using the delete method.

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

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

Working with local databases in Flutter is simple and straightforward, thanks to the sqflite library. With it, we can perform a variety of database operations such as inserting, querying, updating and deleting data.

In summary, data manipulation is a crucial part of application development and Flutter, with its sqflite library, makes this task easier. With a little practice, you'll be comfortable handling local databases in your Flutter apps.

Now answer the exercise about the content:

Which library is used to work with local databases in Flutter?

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

You missed! Try again.

Article image Authentication and security in Flutter

Next page of the Free Ebook:

184Authentication and security in Flutter

3 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou 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