Sub topic 8
Insert, Query, Update and Delete Safely
Assume you know basic Dart classes, null safety, Future, async and await, and have added sqflite to your Flutter project. This chapter uses the notes table created in the previous database chapter.
CRUD means the four main database operations:
- Create inserts a new row.
- Read queries existing rows.
- Update changes a row.
- Delete removes a row.
Each operation should use the sqflite helpers and parameterized conditions.
Map objects to database rows
A database row is represented as a map. A model converts between that map and a Dart object:
class Note {
const Note({this.id, required this.title, this.body});
final int? id;
final String title;
final String? body;
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'body': body,
};
factory Note.fromMap(Map<String, Object?> map) => Note(
id: map['id'] as int?,
title: map['title'] as String,
body: map['body'] as String?,
);
}The id is nullable because a new note does not have an ID until SQLite inserts it.
Implement the CRUD operations
The following functions accept an already-opened Database:
import 'package:sqflite/sqflite.dart';
Future<int> insertNote(Database db, Note note) {
final values = note.toMap()..remove('id');
return db.insert(
'notes',
values,
conflictAlgorithm: ConflictAlgorithm.abort,
);
}
Future<List<Note>> searchNotes(Database db, String term) async {
final rows = await db.query(
'notes',
where: 'title LIKE ? OR body LIKE ?',
whereArgs: ['%$term%', '%$term%'],
orderBy: 'id DESC',
);
return rows.map(Note.fromMap).toList();
}
Future<int> updateNote(Database db, Note note) {
if (note.id == null) {
throw ArgumentError('A note ID is required for an update.');
}
return db.update(
'notes',
{
'title': note.title,
'body': note.body,
},
where: 'id = ?',
whereArgs: [note.id],
);
}
Future<int> deleteNote(Database db, int id) {
return db.delete(
'notes',
where: 'id = ?',
whereArgs: [id],
);
}insert, update, and delete return the number of affected rows, while insert returns the new row ID when successful. A query returns rows, which are converted into Note objects.
The question mark in where is a parameter placeholder. Its matching value goes in whereArgs. SQLite binds the value as data instead of treating it as SQL code.
Understand the operation flow
Check affected rows
An update or delete that matches no row returns 0. Treat that result deliberately:
final changed = await updateNote(
db,
const Note(id: 4, title: 'Updated title'),
);
if (changed == 0) {
throw StateError('No note with ID 4 exists.');
}For several related changes, use a transaction. A transaction groups operations so that either all of them succeed or SQLite rolls them back when one fails.
await db.transaction((txn) async {
await txn.update(
'notes',
{'title': 'Archived'},
where: 'id = ?',
whereArgs: [4],
);
await txn.delete(
'notes',
where: 'id = ?',
whereArgs: [5],
);
});Use transactions when partial completion would leave the app's data inconsistent.
Exercise
Why should a note ID be passed through whereArgs instead of inserted into the SQL string?
Show answer
whereArgs binds the ID as data, which prevents SQL injection and avoids SQL syntax errors caused by untrusted values.