On this page14 sections
Lecture 004: The Database Manager: Delete & Query
| Category | 2: The Database Manager |
| Lecture | 004 of 004 |
| Estimated video length | 20 min |
| Target | Flutter 3.44 · Dart 3.12 · sqflite 2.4 |
| Level | Beginner |
addRecordandupdateRecordchange rows; nowDatabaseStudentneeds to remove one and, just as importantly, read them back asModelStudentobjects a screen can display.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 003: DatabaseStudent, addRecord and updateRecord.
Connection With Previous Lectures
The manager can create and change rows. A screen also needs to remove a student, load the
whole list for a dashboard, and load one specific student by id: the three remaining jobs
this lecture adds to DatabaseStudent.
Learning Objectives
- Delete one row with
db.delete, matched bywhere/whereArgs - Fetch every row with
db.queryand map each one throughModelStudent.fromMap - Return
null(not a crash) when a single-record lookup finds nothing - Notice when a parameter's type doesn't match the column it's compared against
1. Deleting a Row
// lib/data/database_student.dart (continued from Lecture 003)
Future<bool> deleteRecord(String id) async {
try {
Database db = await database;
await db.delete(tableName, where: '$colId = ?', whereArgs: [id]);
return true;
} catch (e) {
print('Error in addRecord: $e');
return false;
}
}deleteRecordtakes aString id, butcolId('id') is declaredINTEGER PRIMARY KEY AUTOINCREMENTin Lecture 001, andModelStudent.idis anint?. This works today because sqflite's underlying SQLite engine compares values loosely enough to still match: but it's the one method in this class whose parameter type doesn't match the column it filters on. See Common Beginner Mistakes.- Same
where: '$colId = ?'+whereArgs: [id]pattern asupdateRecord: never interpolate the id straight into the SQL string. - The
catchblock logs'Error in addRecord'again: copied fromaddRecord, same asupdateRecordin Lecture 003.
2. Reading Every Row
Future<List<ModelStudent>> getAllRecord() async {
List<ModelStudent> list = [];
try {
Database db = await database;
List<Map<String, dynamic>> listMap = await db.query(tableName);
for (Map<String, dynamic> map in listMap) {
list.add(ModelStudent.fromMap(map));
}
return list;
} catch (e) {
print('Error in getAllRecord: $e');
return list;
}
}db.query(tableName)with nowherereturns every row, as aList<Map<String, dynamic>>: the raw shape sqflite always hands back, regardless of how many columns the table has.- The
forloop turns each raw map into aModelStudentwithfromMapand builds the list by hand.listMap.map(ModelStudent.fromMap).toList()does the same thing in one line: see Best Practices. - An empty table and a failed query both return
[]here. That's fine for "no students yet," but it means a screen can't tell the two cases apart from the return value alone: theprintin thecatchis the only trace of a real failure.
3. Reading One Row by Id
Future<ModelStudent?> getRecordById(int id) async {
try {
Database db = await database;
List<Map<String, dynamic>> listMap = await db.query(
tableName,
where: '$colId = ?',
whereArgs: [id],
);
if (listMap.isNotEmpty) {
return ModelStudent.fromMap(listMap.first);
} else {
return null;
}
} catch (e) {
print('Error in getRecordById: $e');
return null;
}
}getRecordByIdtakes anint id: correctly matchingcolId'sINTEGERtype, unlikedeleteRecordabove.- Return type is
ModelStudent?, notModelStudent. "No student with this id" is a normal, expected outcome, not an error, so it's modeled withnull, not a thrown exception or a force-unwrap. listMap.isNotEmptybefore reading.firstavoids aRangeErrorthatlistMap.firstwould throw on an empty list;db.query(..., limit: 1)would also stop SQLite scanning after the first match, which this method doesn't use but could.
Code Examples
Example 1: Using the Full Manager
final db = DatabaseStudent();
final added = await db.addRecord(
ModelStudent(name: 'Ayaan', fatherName: 'Imran Khan', contactNo: '03001234567'),
);
final all = await db.getAllRecord(); // List<ModelStudent>
final first = all.first;
final found = await db.getRecordById(first.id!); // ModelStudent?
print(found?.name); // Ayaan
final deleted = await db.deleteRecord(first.id.toString());
print(deleted); // true
final afterDelete = await db.getRecordById(first.id!);
print(afterDelete); // nullNotice deleteRecord needs first.id.toString() here, while getRecordById takes
first.id! directly: a small, visible cost of the two methods not sharing the same
parameter type.
Common Beginner Mistakes
1. Giving two methods on the same class different parameter types for the same column:
deleteRecord(String id) next to getRecordById(int id) means every call site has to
remember which one wants a String and which wants an int, instead of the compiler
enforcing it. Pick one type (here, int, matching the column) and convert at the edges if
you ever need a String (from a text field, say) rather than threading the wrong type all the
way into whereArgs.
2. Reusing a try/catch block's error message in a method where it no longer applies:
same issue as Lecture 003's updateRecord: deleteRecord's catch still says
'Error in addRecord'. Harmless for now; confusing the day it actually fires.
3. Treating "query failed" and "table is empty" as the same thing: getAllRecord
returns [] either way. A dashboard that shows "No students yet" on an empty list will show
the same message after a real database error, with no hint in the UI that something broke.
4. Calling .first on a list without checking it's non-empty: getRecordById guards
this with listMap.isNotEmpty; skipping that check and calling listMap.first directly
throws a RangeError the moment a lookup legitimately finds nothing.
Best Practices
- Model "might not exist" with a nullable return type (
ModelStudent?), not a sentinel value or a forced unwrap. - Keep a column's Dart parameter type consistent across every method that filters on it:
don't let
Stringandintboth show up for the sameid. listMap.map(ModelStudent.fromMap).toList()is a shorter, equally correct replacement for the hand-writtenforloop ingetAllRecord: reach for it once the loop version makes sense to you.
Mini Challenge
Change deleteRecord's parameter from String id to int id (updating the one call site in
screen_add_update_record.dart that would need it), then add a Future<int> getCount() that
runs SELECT COUNT(*) FROM $tableName with rawQuery and Sqflite.firstIntValue(...) instead
of calling getAllRecord() and reading .length.
Practice Questions
- Why does
getRecordByIdreturnModelStudent?instead ofModelStudent? 2. What's the actual risk ofdeleteRecordtaking aString idwhile the column isINTEGER? 3. What doesgetAllRecordreturn for both an empty table and a failed query, and why is that worth noticing? 4. What doeslistMap.isNotEmptyguard against ingetRecordById?
Practice Answers
- "No row with this id" is an expected, normal outcome, not an error:
nullmodels that without a crash or a fake value. - None today, because SQLite's type affinity coerces the comparison: but it's a guarantee given up for no benefit, and a refactor that relies on strict typing elsewhere could break silently here.
- Both return
[]. A caller can't distinguish "no students yet" from "the query failed" without looking at the console log inside thecatchblock. - It avoids calling
.firston an empty list, which would throw aRangeErrorinstead of letting the method returnnull.
Key Takeaways
deleteRecord,getAllRecordandgetRecordByIdcomplete the five methods onDatabaseStudent: the whole CRUD surface a screen ever needs to call.- A lookup that might find nothing returns a nullable model, never a forced, fake value.
- Keeping a column's Dart type consistent across every method (
int, notStringin one place andintin another) is free correctness the compiler can enforce, if you let it.
Full Code (Copy-Paste Reference)
The complete, finished data layer: every file, as it stands at the end of the course.
Note two quirks kept exactly as taught (and called out above): deleteRecord takes a
String id where the column is INTEGER, and its catch block still logs
'Error in addRecord'. Both are flagged inline below: fix them per the Lecture 003/004 Mini
Challenges before shipping.
lib/data/model_student.dart: the model
class ModelStudent {
int? id; // null until SQLite assigns one on insert
String name;
String fatherName;
String contactNo;
ModelStudent({
this.id,
required this.name,
required this.fatherName,
required this.contactNo,
});
factory ModelStudent.fromMap(Map<String, dynamic> map) {
return ModelStudent(
id: map['id'],
name: map['name'],
fatherName: map['fatherName'],
contactNo: map['contactNo'],
);
}
Map<String, dynamic> toMap() => {
'name': name,
'fatherName': fatherName,
'contactNo': contactNo,
};
}lib/data/database_student.dart: singleton + full CRUD
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
import 'model_student.dart';
// Column-name constants shared by every method below - never a raw string in a query.
String tableName = 'student';
String colId = 'id';
String colName = 'name';
String colFatherName = 'fatherName';
String colContactNo = 'contactNo';
class DatabaseStudent {
DatabaseStudent._();
static DatabaseStudent? databaseStudent;
// Singleton factory: always returns the same instance, one open connection for the app.
factory DatabaseStudent() {
if (databaseStudent == null) {
databaseStudent = DatabaseStudent._();
return databaseStudent!;
} else {
return databaseStudent!;
}
}
static Database? _database;
Future<Database> get database async {
if (_database != null) {
return _database!;
} else {
_database = await initDatabase();
return _database!;
}
}
Future<Database> initDatabase() async {
String path = await getDatabasesPath();
String fullPath = p.join(path, 'student.db');
return openDatabase(
fullPath,
version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE $tableName (
$colId INTEGER PRIMARY KEY AUTOINCREMENT,
$colName TEXT NOT NULL,
$colFatherName TEXT NOT NULL,
$colContactNo TEXT NOT NULL
)
''');
},
);
}
Future<bool> addRecord(ModelStudent modelStudent) async {
try {
Database db = await database;
await db.insert(tableName, modelStudent.toMap());
return true;
} catch (e) {
print('Error in addRecord: $e');
return false;
}
}
Future<bool> updateRecord(ModelStudent modelStudent) async {
try {
Database db = await database;
await db.update(
tableName,
modelStudent.toMap(),
where: '$colId = ?',
whereArgs: [modelStudent.id],
);
return true;
} catch (e) {
// Copy-paste leftover from addRecord - see Lecture 003's Common Beginner Mistakes.
print('Error in addRecord: $e');
return false;
}
}
// Takes String here though colId is INTEGER (and ModelStudent.id is int?) - SQLite's type
// affinity still matches it, but see Common Beginner Mistakes: prefer `int id` instead.
Future<bool> deleteRecord(String id) async {
try {
Database db = await database;
await db.delete(tableName, where: '$colId = ?', whereArgs: [id]);
return true;
} catch (e) {
// Same copy-paste leftover as updateRecord.
print('Error in addRecord: $e');
return false;
}
}
Future<List<ModelStudent>> getAllRecord() async {
List<ModelStudent> list = [];
try {
Database db = await database;
List<Map<String, dynamic>> listMap = await db.query(tableName);
for (Map<String, dynamic> map in listMap) {
list.add(ModelStudent.fromMap(map));
}
return list;
} catch (e) {
print('Error in getAllRecord: $e');
return list; // same [] as "table is empty" - the print above is the only distinction
}
}
Future<ModelStudent?> getRecordById(int id) async {
try {
Database db = await database;
List<Map<String, dynamic>> listMap = await db.query(
tableName,
where: '$colId = ?',
whereArgs: [id],
);
if (listMap.isNotEmpty) {
return ModelStudent.fromMap(listMap.first);
} else {
return null; // "no row with this id" is normal, not an error
}
} catch (e) {
print('Error in getRecordById: $e');
return null;
}
}
}lib/main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(body: Center(child: Text('Sqflite is ready'))),
);
}
}Example usage: insert, read, update, delete:
final db = DatabaseStudent();
final added = await db.addRecord(
ModelStudent(name: 'Ayaan', fatherName: 'Imran Khan', contactNo: '03001234567'),
);
final all = await db.getAllRecord();
final first = all.first;
final found = await db.getRecordById(first.id!);
print(found?.name); // Ayaan
final deleted = await db.deleteRecord(first.id.toString()); // String here, int above
print(deleted); // true