CodeBlanks Logo Icon CodeBlanks

Summary - Database

Combine sqflite, CRUD and transactions to write a user database.

Summary - Database

In this group we learned local database management with Dart. sqflite provides embedded SQLite; Database is the connection object; CRUD operations (insert/query/update/delete) manage data; transaction adds atomicity; drift builds a type-safe ORM on top.

In this summary we combine sqflite setup and a CRUD operation: a setupDb function opens the database and creates a table; an addNote function inserts a note. This is a small but working example of a real application's data layer.

Practice Setup and add a note

The code below imports sqflite. Define setupDb(): open with openDatabase('notes.db'), create the table with db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT)') and return db. Define addNote(Database db): insert with db.insert('notes', {'title': 'Summary note'}). In main add print('Summary: sqflite + CRUD'), await setupDb(), await addNote(db), print('Added: Summary note') and await db.close().

Starter code

main.dart
import 'package:sqflite/sqflite.dart';

Future<Database> setupDb() async {
  // open notes.db, create notes table, return db
}

Future<void> addNote(Database db) async {
  // insert a note (db.insert)
}

void main() async {
  // print summary message, call setupDb and addNote, close
}

Sample solution

main.dart
import 'package:sqflite/sqflite.dart';

Future<Database> setupDb() async {
  final db = await openDatabase('notes.db');
  await db.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT)');
  return db;
}

Future<void> addNote(Database db) async {
  await db.insert('notes', {'title': 'Summary note'});
}

void main() async {
  print('Summary: sqflite + CRUD');
  final db = await setupDb();
  await addNote(db);
  print('Added: Summary note');
  await db.close();
}

Expected output

Summary: sqflite + CRUD
Added: Summary note

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which one is the atomic operation?

  • db.close
  • db.query
  • db.execute
  • Transaction Correct answer

Explanation: a transaction runs multiple operations atomically.

2 Match the database concepts

Term Meaning
sqflite Embedded SQLite
Database Connection
CRUD insert/query/update/delete
drift ORM

3 The db.transaction call

Question
await db.____((txn) async {
    await txn.insert('notes', {'title': 'Summary note'});
  });
Answer
await db.transaction((txn) async {
    await txn.insert('notes', {'title': 'Summary note'});
  });

Explanation: db.transaction starts the atomic block.

All lessons in Advanced