On this page14 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Column Name Constants
  5. 2. The Model Class
  6. 3. Constants in the Database File, Strings in the Model
  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 002: The Student Model & Table Columns

Category1: Sqflite Basics
Lecture002 of 004
Estimated video length16 min
TargetFlutter 3.44 · Dart 3.12 · sqflite 2.4
LevelBeginner

A table row is just a Map<String, dynamic>: sqflite has no idea about your Student class. We write a small model with toMap() and fromMap() so the rest of the app never touches a raw map.

Contents

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


Prerequisites

Lecture 001 and Dart classes with named constructors and factory constructors.


Connection With Previous Lectures

Lecture 001 created a table with four columns and a singleton, DatabaseStudent, to hold the open connection. Every sqflite method (insert, update, query) reads and writes Map<String, dynamic>, not a Dart object. This lecture writes the translation layer between the two: ModelStudent.


Learning Objectives

  • Write a model class with a toMap() method
  • Write a matching fromMap() factory constructor
  • Explain why the model's fields are plain, mutable fields here: not final
  • Know where column-name constants belong, and the risk of not using them everywhere

1. Column Name Constants

dart
// lib/data/database_student.dart
String tableName = 'student';
String colId = 'id';
String colName = 'name';
String colFatherName = 'fatherName';
String colContactNo = 'contactNo';

These constants live next to the singleton in database_student.dart (Lecture 001) because the manager methods in Lectures 003–004 build every query from them, never from a typed-out string. Misspell 'fatherNam' in a raw string and SQLite silently treats it as a new column with no data; misspell colFatherNam and the analyzer refuses to compile.

2. The Model Class

dart
// lib/data/model_student.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() => {
    // 'id': id,
    'name': name,
    'fatherName': fatherName,
    'contactNo': contactNo,
  };
}
  • id is nullable: a brand-new student has no row yet, so no id. INTEGER PRIMARY KEY AUTOINCREMENT fills one in once the row is inserted (Lecture 003).
  • toMap() leaves the id key commented out: handing sqflite's insert an 'id': null entry works too, but leaving the key out entirely is clearer about intent: "let SQLite choose the id." Uncomment it only for the update call in Lecture 003, where the row already has a real id.
  • The fields are not final: unlike a typical immutable model, name, fatherName and contactNo can be reassigned after construction. That's a deliberate trade-off here: the add/update screen builds one ModelStudent straight from its TextEditingControllers and hands it to either addRecord or updateRecord, there's no separate "build a changed copy" step to write.
  • fromMap() is a factory constructor: it builds the finished object in one step from a map, instead of a separate constructor plus assignment logic.
  • Map<String, dynamic>, not Map<String, Object?> with casts: this model trusts the map's values to already be the right type. That's simpler to read, but see the mistakes section below for the cost.

3. Constants in the Database File, Strings in the Model

Notice toMap() / fromMap() use the literal strings 'name', 'fatherName', 'contactNo': not the colName / colFatherName / colContactNo constants from Lecture 1. That works because the literals and the constants currently hold identical text, but it means two files must be kept in sync by hand. Lectures 003–004 import database_student.dart for every query, so a rename there would need a matching rename here too: the Best Practices section below shows the safer alternative.


Code Examples

Example 1: Building a New Student Before Saving

dart
final newStudent = ModelStudent(
  name: 'Ayaan',
  fatherName: 'Imran Khan',
  contactNo: '03001234567',
);

print(newStudent.toMap());
// {name: Ayaan, fatherName: Imran Khan, contactNo: 03001234567}

Notice there is no id key at all: toMap() leaves it commented out until the row has been inserted and a real id comes back from SQLite.


Common Beginner Mistakes

1. Writing raw strings in every query ('fatherNam') instead of a constant: a typo compiles fine and fails silently at run time.

2. Making id non-nullable: then there is no legal value to give a student before it is saved, and code reaches for -1 or 0 as a fake id, which can collide with a real row.

3. Trusting Map<String, dynamic> without ever checking it: map['name'] is dynamic here, so a column that's null in the database (if NOT NULL were ever dropped) crashes at the String name assignment with a run-time type error instead of a compile-time warning. Explicit casts (as String) at least fail at the same line that's wrong.

4. Letting the model's hardcoded strings drift from the database file's constants: rename colFatherName's value without updating fromMap/toMap to match, and rows silently stop round-tripping that field.


Best Practices

  • Column names live as constants in database_student.dart, shared by every manager method.
  • The safer version of this model imports those constants and uses map[colName] instead of map['name']: one rename then updates every file that matters.
  • Keep all database code in one folder; screens should only ever see ModelStudent, never a raw Map.

Mini Challenge

Change the model's fromMap()/toMap() to use colName, colFatherName and colContactNo from database_student.dart instead of the raw string literals shown above, then rename colContactNo's value (not the constant name) to 'contact_no' and confirm only one line needs to change.


Practice Questions

  1. Why is id nullable on the model? 2. Why are name, fatherName and contactNo not final on ModelStudent, unlike a typical immutable model? 3. Why use a factory constructor for fromMap? 4. What goes wrong if the model's map keys drift from the database file's column constants?

Practice Answers

  1. A new, unsaved student has no row id yet; null represents "not saved."
  2. The add/update screen reuses the same mutable object for both building the form and saving it, instead of constructing a fresh immutable copy on every keystroke.
  3. It builds the finished object directly from the map in one expression instead of needing a separate constructor and no-op fields.
  4. SQLite does not error: a renamed column just silently has no data under the old key, which looks like a logic bug, not a typo.

Key Takeaways

  • toMap() turns a model into what sqflite can store; fromMap() turns a row back into a model.
  • This model's fields are deliberately mutable, matching how the add/update screen builds and reuses one ModelStudent from its text controllers.
  • Column-name constants belong in one file (database_student.dart); hardcoding the same strings in the model works only as long as nobody renames one side and forgets the other.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. CRUD methods still arrive in Lectures 003–004.

lib/data/database_student.dart: singleton + table

dart
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.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
          )
        ''');
      },
    );
  }

  // addRecord / updateRecord / deleteRecord / getAllRecord / getRecordById → Lectures 003–004
}

lib/data/model_student.dart: the model

dart
class ModelStudent {
  int? id; // null until SQLite assigns one on insert - a new student has no row yet
  String name;
  String fatherName;
  String contactNo;

  // Fields are mutable on purpose: the add/update screen builds one ModelStudent from
  // its TextEditingControllers and reuses it, rather than constructing an immutable copy.
  ModelStudent({
    this.id,
    required this.name,
    required this.fatherName,
    required this.contactNo,
  });

  // Builds the object directly from a raw sqflite row in one step.
  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() => {
    // 'id' deliberately left out: let SQLite's AUTOINCREMENT choose it on insert.
    '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'))),
    );
  }
}