On this page17 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Why a SQL Database
  5. 2. What Is Sqflite
  6. 3. The Three Moving Parts
  7. 4. Create the Project and Add Packages
  8. 5. The Folder Layout
  9. 6. A Singleton That Opens the Database Once
  10. Code Examples
  11. Common Beginner Mistakes
  12. Best Practices
  13. Mini Challenge
  14. Practice Questions
  15. Practice Answers
  16. Key Takeaways
  17. Full Code (Copy-Paste Reference)

Lecture 001: What Is Sqflite & Project Setup

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

Hive saves a Dart object as a whole. Sqflite saves rows in a table, read back with real SQL: SELECT, WHERE, joins. It is the same SQLite engine that ships inside every Android and iOS phone, with a Dart API in front of it.

Contents

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


Prerequisites

  • Dart classes, named constructors and factory constructors; Future, async and await
  • A running Flutter app: Scaffold, AppBar, StatefulWidget (Essential Widgets 001)

Connection With Previous Lectures

Earlier courses either kept data in a variable (gone when the app closes) or, in the Hive course, in a box keyed by a single field. This course builds a students table (one row per student, with an id, a name, a father's name, and a contact number) and reads it back with SQL instead of a key lookup.


Learning Objectives

By the end of this lecture you will be able to:

  • Explain what sqflite is and when SQL beats a key-value box
  • Add sqflite and path to a project
  • Write a singleton class that opens the database exactly once
  • Describe openDatabase, onCreate and a CREATE TABLE statement

1. Why a SQL Database

StorageLooks up byGood at
A variable or listnothing: gone on closenothing persistent
Hive boxone keyfast key → object, no relations
sqflite tableany column, via SQLrows, filtering, sorting, relations

Sqflite is a good fit once you need to filter ("every student added this week"), sort, or join more than one table. For a single settings blob or a simple cache, Hive is simpler.

2. What Is Sqflite

  • A table, not a box: a grid of rows and named columns, same as a spreadsheet.
  • Real SQL: you write CREATE TABLE, INSERT, UPDATE, DELETE, SELECT as text.
  • One file on disk: the whole database lives in a single .db file inside the app's own folder, found with getDatabasesPath().
  • Cross-platform: Android and iOS both ship SQLite already; the plugin just talks to it.

3. The Three Moving Parts

This course keeps all three in one class, DatabaseStudent:

  1. A singleton + the database connection: built once, reused everywhere (this lecture).
  2. A model, ModelStudent: toMap() / fromMap() turn a row into an object and back (Lecture 002).
  3. Manager methods on the same class: insert, update, delete and query, all living next to the connection they use (Lectures 003–004).

4. Create the Project and Add Packages

bash
flutter create sqflite_demo
cd sqflite_demo
flutter pub add sqflite path
  • sqflite: the database plugin itself.
  • path: joins the database file name to the platform's databases folder correctly on every OS (p.join, not string concatenation with /). Sqflite already pulls path in as a transitive dependency, so an import without this step still compiles: but flutter_lints' depend_on_referenced_packages rule will warn until it's declared directly in pubspec.yaml.

5. The Folder Layout

output
lib/
  main.dart
  data/
    model_student.dart       ← the model (Lecture 002)
    database_student.dart    ← the singleton + manager (Lectures 002–004)
  screen_home.dart            ← the list (not covered in detail in this course)
  screen_add_update_record.dart  ← the add/update form (not covered in detail)

Everything that touches the database lives in data/; screens only call DatabaseStudent().

6. A Singleton That Opens the Database Once

dart
// lib/data/database_student.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
}
  • DatabaseStudent._(): a private named constructor; nothing outside this file can call it, so the only way to get an instance is through the factory below.
  • factory DatabaseStudent(): looks like a normal constructor call (DatabaseStudent()) from every screen, but returns the same instance every time instead of building a new one. This is the singleton pattern: one database connection for the whole app.
  • database is a lazy getter: the first call opens the file with initDatabase(); every call after that reuses the cached _database field instead of reopening the file.
  • getDatabasesPath(): the folder sqflite is allowed to write to; never hard-code a path.
  • p.join(...): builds the file path with the right separator for the current platform.
  • version: 1: bump this and add an onUpgrade callback when you later change the schema.
  • onCreate: runs once, the first time the file is created. It never runs again, even if you edit the CREATE TABLE text later (Lecture 003 covers why that matters).
  • INTEGER PRIMARY KEY AUTOINCREMENT: SQLite fills this column in automatically on insert when you don't provide one, and never reuses an id after a row is deleted.

Code Examples

Example 1: Proof That Sqflite Is Installed

dart
// lib/main.dart
import 'package:flutter/material.dart';

import 'data/database_student.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(body: Center(child: Text('Sqflite is ready'))),
    );
  }
}

The database itself doesn't need to be opened in main(): the database getter on DatabaseStudent() opens it lazily the first time any screen actually asks for it.


Common Beginner Mistakes

1. Building the path with string concatenation ('$path/student.db'): works on one platform and breaks on another. Always use path's p.join.

2. Forgetting to return after assigning the cached field in a lazy getter: writing _database = await initDatabase(); with no return after it means the first call still falls through to the end of the function and hands back null, even though _database now holds a real value. Every lazy getter needs an explicit return on both branches.

3. Expecting onCreate to run again after editing the table: it only runs when the file does not exist yet. Delete the app's data (or bump version with an onUpgrade) to see schema changes during development.


Best Practices

  • Keep table and column names as top-level String constants in one place: Lecture 002 shows why.
  • Give every column a type and NOT NULL unless you expect missing values.
  • Keep all database code in one folder (data/); screens should not know SQL.
  • Open the connection through a singleton's lazy getter, never by calling openDatabase directly from a screen.

Mini Challenge

Create a new project, add the two packages, call DatabaseStudent().database once on startup, and confirm (with a print statement) that calling it a second time does not print anything from inside initDatabase(): proof the connection is cached.


Practice Questions

  1. What does sqflite save that Hive does not know how to query directly? 2. What problem does the singleton factory constructor solve here? 3. When does onCreate run? 4. Why use path's p.join instead of string concatenation?

Practice Answers

  1. Rows across named columns, searchable and filterable with SQL: not just a value under a single key.
  2. It guarantees every screen that calls DatabaseStudent() gets the same object, so the database file is only ever opened once.
  3. Only the first time the database file is created.
  4. It builds a correct path separator on every platform sqflite runs on.

Key Takeaways

  • Sqflite stores rows in SQL tables inside one file, opened with openDatabase.
  • A private constructor plus a factory constructor is the standard Dart way to write a singleton: one DatabaseStudent instance, one open connection, for the whole app.
  • onCreate runs the CREATE TABLE statement once, the first time the file is created.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. The CRUD methods (addRecord, updateRecord, deleteRecord, getAllRecord, getRecordById) arrive in Lectures 003–004: this file only opens the connection and creates the table so far.

lib/data/database_student.dart: singleton + table

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

// Column-name constants, shared by every manager method added in later lectures.
// Using these instead of raw strings means a typo fails to compile, not fails silently.
String tableName = 'student';
String colId = 'id';
String colName = 'name';
String colFatherName = 'fatherName';
String colContactNo = 'contactNo';

class DatabaseStudent {
  // Private constructor - nothing outside this file can build one directly.
  DatabaseStudent._();

  static DatabaseStudent? databaseStudent;

  // Looks like a normal constructor call from every screen, but always returns
  // the SAME instance - one database connection for the whole app.
  factory DatabaseStudent() {
    if (databaseStudent == null) {
      databaseStudent = DatabaseStudent._();
      return databaseStudent!;
    } else {
      return databaseStudent!;
    }
  }

  static Database? _database;

  // Lazy getter: opens the file on the first call, then reuses the cached connection.
  Future<Database> get database async {
    if (_database != null) {
      return _database!;
    } else {
      _database = await initDatabase();
      return _database!;
    }
  }

  Future<Database> initDatabase() async {
    String path = await getDatabasesPath(); // the folder sqflite is allowed to write to
    String fullPath = p.join(path, 'student.db'); // correct separator on every platform

    return openDatabase(
      fullPath,
      version: 1,
      // Runs ONCE - only the first time this file is created, never again after that.
      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/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,
      // No database call here on purpose - the `database` getter opens the file
      // lazily, the first time any screen actually asks for it.
      home: Scaffold(body: Center(child: Text('Sqflite is ready'))),
    );
  }
}