CHAPTER 21
Beginner
SQLite Database in Flutter
Updated: May 16, 2026
35 min read
# CHAPTER 21
SQLite Database in Flutter
1. Introduction
Shared Preferences works perfectly for a username or a high score. But what if you are building an offline Notes app, an Expense Tracker, or a robust To-Do list? You need to sort items by date, filter them by category, and update thousands of records instantly. You need a real database. In this chapter, we will master the SQLite Database in Flutter. We will install the powerfulsqflite package to embed a fully functional SQL relational database directly into the user's phone, allowing us to perform high-speed offline CRUD (Create, Read, Update, Delete) operations.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Install the
sqfliteandpathpackages.
- Initialize an embedded SQLite database.
- Create SQL tables with primary keys and data types.
- Execute raw SQL queries or use built-in helper methods.
- Perform CRUD operations (Insert, Query, Update, Delete).
3. Setup and Installation
To work with SQLite, you need two packages. Add them topubspec.yaml:
yaml
4. Creating the Database Helper
Because opening a database connection is an expensive, asynchronous operation, we create a Singleton class calledDatabaseHelper. This ensures the app only opens the database once, and reuses that connection everywhere.
dart
5. Performing CRUD Operations
Once the table is created, we write methods inside ourDatabaseHelper to interact with it.
CREATE (Insert):
dart
READ (Query):
dart
UPDATE:
dart
DELETE:
dart
6. Integrating with the UI
When the screen opens, you fetch the notes and display them. BecausegetAllNotes returns a Future, you can use setState to update the UI once the data arrives from the database.
dart
7. Visual Learning: Local vs Cloud
txt
8. Common Mistakes
-
SQL Injection Vulnerabilities: Notice in the Update/Delete methods we used
where: 'id = ?', whereArgs: [id]. Beginners often try to manually concatenate strings:where: 'id = $id'. NEVER DO THIS. If a user types malicious SQL code into a text box, string concatenation will execute it and delete your entire database. ALWAYS use the?parameters (whereArgs), which securely sanitizes the input!
9. Best Practices
-
Use Model Classes: Just like we did with JSON parsing in Chapter 19, you should never pass raw Maps to your UI. Create a
Noteclass withfromMap()andtoMap()methods. YourgetAllNotesmethod should return aList<Note>, ensuring your UI is strictly typed and protected from typo crashes.
10. Practice Exercises
- 1. What official package allows you to embed a relational SQL database directly into a Flutter application?
-
2.
Write the raw SQL statement required to create a table named
userswith anid(integer) andname(text).
11. MCQs with Answers
Question 1
When creating a DatabaseHelper class in Dart to manage a local database, why is the "Singleton" pattern (having a private constructor and a single static instance) universally recommended?
Question 2
When executing an update or delete query in sqflite, what is the purpose of the whereArgs: [id] property?
12. Interview Questions
-
Q: Explain the necessity of the
pathpackage when configuringsqflite. Why can't a developer simply hardcode a file path likeC:/app/database.db?
-
Q: Describe the security risks of manually concatenating variables into SQL strings. How does
sqflitemitigate this risk through parameterized queries?
-
Q: Compare the architectural use cases of
shared_preferencesversussqflite. Provide a specific app feature that mandates the use ofsqflite.
13. FAQs
Q: Can I view my SQLite database file visually? A: Yes! On the Android Emulator, you can use Android Studio's "Device File Explorer" to navigate todata/data/com.yourcompany.yourapp/databases/, download the .db file, and open it with a free visual tool like "DB Browser for SQLite".
14. Summary
In Chapter 21, we brought robust offline capabilities to our application. We installed thesqflite package, securely locating the correct device directory using the path package. We architected a Singleton DatabaseHelper to efficiently manage a single open connection, wrote raw SQL to generate our tables, and executed parameterized queries to safely perform CRUD operations without exposing the app to SQL injection attacks. Our app can now store and query massive datasets entirely offline.