On this page14 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Deleting a Row
  5. 2. Reading Every Row
  6. 3. Reading One Row by Id
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Mini Challenge
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 004: The Database Manager: Delete & Query

Category2: The Database Manager
Lecture004 of 004
Estimated video length20 min
TargetFlutter 3.44 · Dart 3.12 · sqflite 2.4
LevelBeginner

addRecord and updateRecord change rows; now DatabaseStudent needs to remove one and, just as importantly, read them back as ModelStudent objects 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 by where / whereArgs
  • Fetch every row with db.query and map each one through ModelStudent.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

dart
// 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;
  }
}
  • deleteRecord takes a String id, but colId ('id') is declared INTEGER PRIMARY KEY AUTOINCREMENT in Lecture 001, and ModelStudent.id is an int?. 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 as updateRecord: never interpolate the id straight into the SQL string.
  • The catch block logs 'Error in addRecord' again: copied from addRecord, same as updateRecord in Lecture 003.

2. Reading Every Row

dart
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 no where returns every row, as a List<Map<String, dynamic>>: the raw shape sqflite always hands back, regardless of how many columns the table has.
  • The for loop turns each raw map into a ModelStudent with fromMap and 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: the print in the catch is the only trace of a real failure.

3. Reading One Row by Id

dart
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;
  }
}
  • getRecordById takes an int id: correctly matching colId's INTEGER type, unlike deleteRecord above.
  • Return type is ModelStudent?, not ModelStudent. "No student with this id" is a normal, expected outcome, not an error, so it's modeled with null, not a thrown exception or a force-unwrap.
  • listMap.isNotEmpty before reading .first avoids a RangeError that listMap.first would 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

dart
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);                              // null

Notice 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 String and int both show up for the same id.
  • listMap.map(ModelStudent.fromMap).toList() is a shorter, equally correct replacement for the hand-written for loop in getAllRecord: 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

  1. Why does getRecordById return ModelStudent? instead of ModelStudent? 2. What's the actual risk of deleteRecord taking a String id while the column is INTEGER? 3. What does getAllRecord return for both an empty table and a failed query, and why is that worth noticing? 4. What does listMap.isNotEmpty guard against in getRecordById?

Practice Answers

  1. "No row with this id" is an expected, normal outcome, not an error: null models that without a crash or a fake value.
  2. 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.
  3. Both return []. A caller can't distinguish "no students yet" from "the query failed" without looking at the console log inside the catch block.
  4. It avoids calling .first on an empty list, which would throw a RangeError instead of letting the method return null.

Key Takeaways

  • deleteRecord, getAllRecord and getRecordById complete the five methods on DatabaseStudent: 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, not String in one place and int in 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

dart
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

dart
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

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:

dart
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