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

Lecture 003: The Database Manager: Create & Update

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

Screens should not know how sqflite works. Every database call lives in one class (DatabaseStudent, the singleton from Lecture 001) so a screen only ever says "save this student" or "update that one."

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lectures 001–002: the DatabaseStudent singleton and its database getter, the student table, ModelStudent, and toMap()/fromMap().


Connection With Previous Lectures

Lecture 001 built a singleton that opens the database once. Lecture 002 built a model that turns a row into an object and back. Neither one saves anything yet: that's what addRecord and updateRecord do, as two more methods on the same DatabaseStudent class.


Learning Objectives

  • Insert a row with db.insert and report success or failure to the caller
  • Update a row with db.update, matched by where / whereArgs
  • Explain why every manager method goes through the same try / catch shape
  • Spot two easy mistakes to make when a method is copy-pasted to write the next one

1. Insert a Row

dart
// lib/data/database_student.dart (continued from Lecture 001)
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;
  }
}
  • modelStudent.toMap() leaves out id (Lecture 002), so db.insert lets the INTEGER PRIMARY KEY AUTOINCREMENT column assign one. Unlike some sqflite examples, addRecord here does not hand that generated id back to the caller: it only reports true/false. If a screen needs the new id immediately (to navigate to a detail view, for example), that's a one-line change: return await db.insert(...) > 0; becomes final id = await db.insert(...); return id; with the return type changed to Future<int>.
  • try / catch around every database call: a locked file, a disk error, or a bad value all surface as an exception; wrapping each method the same way means every call site gets a bool back instead of needing its own exception handling.

2. Update a Row

dart
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) {
    print('Error in addRecord: $e');
    return false;
  }
}
  • where: '$colId = ?' + whereArgs: [modelStudent.id]: the ? is a placeholder sqflite fills in safely; never interpolate the id straight into the string ('id = ${modelStudent.id}'). That opens the door to SQL injection the same way raw string SQL does in any language.
  • modelStudent.toMap() still leaves out id: which is correct here too, since id is the column being matched in where, not a column being overwritten in the SET list.
  • Look closely at the catch block: it prints 'Error in addRecord: $e', inside updateRecord. That's not a typo in this article; it's copied straight from the saved project file. See Common Beginner Mistakes.

Code Examples

Example 1: Insert Then Update

dart
final db = DatabaseStudent();

final added = await db.addRecord(
  ModelStudent(name: 'Ayaan', fatherName: 'Imran Khan', contactNo: '03001234567'),
);
print(added); // true

final all = await db.getAllRecord(); // Lecture 004
final saved = all.first;

saved.name = 'Ayaan Khan';
final updated = await db.updateRecord(saved);
print(updated); // true

Because ModelStudent's fields are mutable (Lecture 002), the update path reassigns a field on the record you already loaded, rather than constructing a brand-new object by hand.


Common Beginner Mistakes

1. Not await-ing db.insert / db.update before returning true: the method above writes await db.insert(...), but it's easy to drop the await when typing quickly:

dart
Future<bool> addRecord(ModelStudent modelStudent) async {
  try {
    Database db = await database;
    db.insert(tableName, modelStudent.toMap()); // missing await
    return true;
  } catch (e) {
    print('Error in addRecord: $e');
    return false;
  }
}

This still mostly "works," because sqflite queues every call made on the same Database in order: but the try/catch around it stops catching anything. db.insert(...) returns a Future that nobody is waiting on, so if the insert fails after this function has already returned true, that exception has nowhere to go but an unhandled error in Flutter's error zone, and the caller already believes the save succeeded.

2. Copy-pasting a try/catch block and forgetting to update the label inside it: the real updateRecord above logs 'Error in addRecord', because the whole method was copied from addRecord and only the call in the try block was changed. Harmless until the day an update actually fails and the console tells you to go debug the wrong method.

3. Collapsing every outcome into true/false: a locked database, a constraint violation, and a genuine bug in your own code all come back from addRecord as the same false. The print at least puts the real exception in the console during development; don't remove it without replacing it with real logging.


Best Practices

  • Keep every manager method's shape consistent: open the database, run one statement inside try/catch, return a simple result the screen can act on.
  • Always parameterize where clauses with ? and whereArgs; never build SQL with string interpolation.
  • When copying a method to write a similar one, re-read every string literal inside it: error messages are exactly the kind of text that silently survives a copy-paste unchanged.

Mini Challenge

Fix the updateRecord error log so it prints 'Error in updateRecord: $e' instead of 'Error in addRecord: $e', then change addRecord's return type to Future<int> so it hands the new row's id back to the caller instead of just true/false.


Practice Questions

  1. Why does addRecord call modelStudent.toMap() instead of building a map by hand? 2. What breaks, and what doesn't, if await is dropped before db.insert(...)? 3. Why is where: '$colId = ?' safer than string interpolation? 4. What's the actual bug in updateRecord's catch block, and why doesn't it stop the method from working?

Practice Answers

  1. toMap() is the single place that knows how a ModelStudent becomes the Map<String, dynamic> sqflite expects: reusing it keeps the model's shape in one file.
  2. The insert still happens (sqflite queues it), but the surrounding try/catch no longer catches a failure that happens inside that unobserved Future, and the method may already have returned true.
  3. The value is bound safely instead of being spliced into the SQL text, which rules out SQL injection.
  4. It logs 'Error in addRecord' instead of 'Error in updateRecord': a copy-paste leftover. It doesn't stop the update from running; it only makes the console message misleading if an error is ever actually thrown.

Key Takeaways

  • addRecord and updateRecord are both methods on the same DatabaseStudent singleton from Lecture 001: there is no second class to open or manage.
  • where clauses are always parameterized with ? and whereArgs: never built with string interpolation.
  • A method born from copy-pasting another one needs its own read-through, especially its string literals: the compiler won't catch a wrong log message.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. deleteRecord, getAllRecord and getRecordById still arrive in Lecture 004.

lib/data/database_student.dart: singleton, table & create/update

dart
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';

import 'model_student.dart';

String tableName = 'student';
String colId = 'id';
String colName = 'name';
String colFatherName = 'fatherName';
String colContactNo = 'contactNo';

class DatabaseStudent {
  DatabaseStudent._();

  static DatabaseStudent? databaseStudent;

  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;
      // toMap() leaves out 'id' - AUTOINCREMENT assigns it for us.
      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(),
        // '?' is a safe placeholder sqflite fills in - never splice the id into the string.
        where: '$colId = ?',
        whereArgs: [modelStudent.id],
      );
      return true;
    } catch (e) {
      // NOTE: copied from addRecord - this label should say "updateRecord" (see Common
      // Beginner Mistakes above). Kept as-is here to match the saved course project exactly.
      print('Error in addRecord: $e');
      return false;
    }
  }

  // deleteRecord / getAllRecord / getRecordById → Lecture 004
}

lib/data/model_student.dart: the model

dart
class ModelStudent {
  int? id;
  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/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'))),
    );
  }
}