On this page17 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. Why a SQL Database
- 2. What Is Sqflite
- 3. The Three Moving Parts
- 4. Create the Project and Add Packages
- 5. The Folder Layout
- 6. A Singleton That Opens the Database Once
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Key Takeaways
- Full Code (Copy-Paste Reference)
Lecture 001: What Is Sqflite & Project Setup
| Category | 1: Sqflite Basics |
| Lecture | 001 of 004 |
| Estimated video length | 16 min |
| Target | Flutter 3.44 · Dart 3.12 · sqflite 2.4 |
| Level | Beginner |
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,asyncandawait - 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
sqfliteandpathto a project - Write a singleton class that opens the database exactly once
- Describe
openDatabase,onCreateand aCREATE TABLEstatement
1. Why a SQL Database
| Storage | Looks up by | Good at |
|---|---|---|
| A variable or list | nothing: gone on close | nothing persistent |
Hive box | one key | fast key → object, no relations |
sqflite table | any column, via SQL | rows, 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,SELECTas text. - One file on disk: the whole database lives in a single
.dbfile inside the app's own folder, found withgetDatabasesPath(). - 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:
- A singleton + the database connection: built once, reused everywhere (this lecture).
- A model,
ModelStudent:toMap()/fromMap()turn a row into an object and back (Lecture 002). - 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
flutter create sqflite_demo
cd sqflite_demo
flutter pub add sqflite pathsqflite: 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 pullspathin as a transitive dependency, so an import without this step still compiles: butflutter_lints'depend_on_referenced_packagesrule will warn until it's declared directly inpubspec.yaml.
5. The Folder Layout
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
// 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 thefactorybelow.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.databaseis a lazy getter: the first call opens the file withinitDatabase(); every call after that reuses the cached_databasefield 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 anonUpgradecallback when you later change the schema.onCreate: runs once, the first time the file is created. It never runs again, even if you edit theCREATE TABLEtext 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
// 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
Stringconstants in one place: Lecture 002 shows why. - Give every column a type and
NOT NULLunless 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
openDatabasedirectly 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
- What does sqflite save that Hive does not know how to query directly? 2. What problem does
the singleton
factoryconstructor solve here? 3. When doesonCreaterun? 4. Why usepath'sp.joininstead of string concatenation?
Practice Answers
- Rows across named columns, searchable and filterable with SQL: not just a value under a single key.
- It guarantees every screen that calls
DatabaseStudent()gets the same object, so the database file is only ever opened once. - Only the first time the database file is created.
- 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
factoryconstructor is the standard Dart way to write a singleton: oneDatabaseStudentinstance, one open connection, for the whole app. onCreateruns theCREATE TABLEstatement 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
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
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'))),
);
}
}