Learn/Local Storage/SQLite with sqflite

SQLite with sqflite

Use SQL queries for structured relational data in Flutter

7 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Schema And Migration Strategy
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

SQLite with sqflite

sqflite brings the full power of SQLite to Flutter. SQLite is a relational database, which means your data is organized into tables with rows and columns, and you can write SQL queries to filter, sort, join, and aggregate data. Use sqflite when your app needs complex data relationships (for example, users who have many orders, each with many items), or when you need to search and filter large datasets efficiently. It is more setup than Hive or SharedPreferences, but gives you much more querying power.

dart
1// pubspec.yaml: sqflite: ^2.3.0, path: ^1.8.3
2import 'package:sqflite/sqflite.dart';
3import 'package:path/path.dart';
4
5class DatabaseHelper {
6 static Database? _database;
7
8 Future<Database> get database async {
9 _database ??= await _initDB();
10 return _database!;
11 }
12
13 Future<Database> _initDB() async {
14 final path = join(await getDatabasesPath(), 'app.db');
15 return openDatabase(
16 path,
17 version: 1,
18 onCreate: (db, version) async {
19 await db.execute('''
20 CREATE TABLE tasks (
21 id INTEGER PRIMARY KEY AUTOINCREMENT,
22 title TEXT NOT NULL,
23 isDone INTEGER DEFAULT 0,
24 createdAt TEXT
25 )
26 ''');
27 },
28 );
29 }
30
31 // ── INSERT ──
32 Future<int> insertTask(Map<String, dynamic> task) async {
33 final db = await database;
34 return db.insert('tasks', task);
35 }
36
37 // ── READ ALL ──
38 Future<List<Map<String, dynamic>>> getTasks() async {
39 final db = await database;
40 return db.query('tasks', orderBy: 'createdAt DESC');
41 }
42
43 // ── UPDATE ──
44 Future<int> updateTask(int id, Map<String, dynamic> data) async {
45 final db = await database;
46 return db.update('tasks', data, where: 'id = ?', whereArgs: [id]);
47 }
48
49 // ── DELETE ──
50 Future<int> deleteTask(int id) async {
51 final db = await database;
52 return db.delete('tasks', where: 'id = ?', whereArgs: [id]);
53 }
54}

sqflite vs Hive

💡 sqflite vs Hive

Use sqflite when you need relational queries like JOINs, WHERE clauses, or ORDER BY. Use Hive for simpler key-value or object storage where read/write speed matters most and you do not need SQL.

Schema And Migration Strategy

SQL power is valuable only when schema evolution is controlled. Plan for change:

  • Keep CREATE TABLE statements versioned and easy to audit.
  • Use database version bumps with migration scripts for every schema change.
  • Prefer adding nullable columns before destructive column removals.
  • Wrap multi-step migrations in transactions to avoid half-applied states.

Treat migrations as production code. A single broken migration can block app startup for all existing users.

SQL Safety Rules

  • Use parameterized whereArgs instead of string interpolation.
  • Keep table and column names in constants to avoid typo bugs.
  • Index frequently filtered columns for better performance.
  • Convert booleans and dates consistently when storing and reading rows.
  • Catch and log database exceptions with enough context to debug quickly.

SQLite QA Checklist

  • Fresh install creates schema correctly and inserts first record successfully.
  • Upgrade from previous DB version migrates without data loss.
  • Update and delete operations affect exactly one intended row.
  • Sort and filter queries return expected order and count.
  • Database failure paths are handled without app crashes.

This Lesson In Simple Words

Use SQL queries for structured relational data in Flutter. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Which method is used to create tables when the database is first opened?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • bloc: An event-to-state pattern that separates logic from UI.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Connect this lesson to separation of concerns so your codebase stays maintainable as it grows.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "SQLite with sqflite" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Moving forward without checking whether the current concept is truly clear.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Which method is used to create tables when the database is first opened?

The onCreate callback in openDatabase() runs when the database file is created for the first time.

How do you prevent SQL injection in sqflite?

Using ? placeholders with whereArgs (parameterized queries) prevents SQL injection attacks.

What does db.query() return?

sqflite returns query results as a List of Maps, where each Map represents a row.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue