On this page13 sections
Lecture 003: The Database Manager: Create & Update
| Category | 2: The Database Manager |
| Lecture | 003 of 004 |
| Estimated video length | 20 min |
| Target | Flutter 3.44 · Dart 3.12 · sqflite 2.4 |
| Level | Beginner |
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.insertand report success or failure to the caller - Update a row with
db.update, matched bywhere/whereArgs - Explain why every manager method goes through the same
try/catchshape - Spot two easy mistakes to make when a method is copy-pasted to write the next one
1. Insert a Row
// 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 outid(Lecture 002), sodb.insertlets theINTEGER PRIMARY KEY AUTOINCREMENTcolumn assign one. Unlike some sqflite examples,addRecordhere does not hand that generated id back to the caller: it only reportstrue/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;becomesfinal id = await db.insert(...); return id;with the return type changed toFuture<int>.try/catcharound 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 aboolback instead of needing its own exception handling.
2. Update a Row
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 outid: which is correct here too, sinceidis the column being matched inwhere, not a column being overwritten in theSETlist.- Look closely at the
catchblock: it prints'Error in addRecord: $e', insideupdateRecord. 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
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); // trueBecause 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:
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
whereclauses with?andwhereArgs; 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
- Why does
addRecordcallmodelStudent.toMap()instead of building a map by hand? 2. What breaks, and what doesn't, ifawaitis dropped beforedb.insert(...)? 3. Why iswhere: '$colId = ?'safer than string interpolation? 4. What's the actual bug inupdateRecord'scatchblock, and why doesn't it stop the method from working?
Practice Answers
toMap()is the single place that knows how aModelStudentbecomes theMap<String, dynamic>sqflite expects: reusing it keeps the model's shape in one file.- The insert still happens (sqflite queues it), but the surrounding
try/catchno longer catches a failure that happens inside that unobservedFuture, and the method may already have returnedtrue. - The value is bound safely instead of being spliced into the SQL text, which rules out SQL injection.
- 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
addRecordandupdateRecordare both methods on the sameDatabaseStudentsingleton from Lecture 001: there is no second class to open or manage.whereclauses are always parameterized with?andwhereArgs: 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
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
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
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'))),
);
}
}