Contents
Coding With Dhrumil

HomeArticles

Flutter SQLite Database Example: A Practical Local Storage Guide

By Dhrumil PatelPublished 4 min read

Almost every Flutter app eventually needs to store something that must survive a restart: a note list, a download queue, a cached profile. SQLite remains the most predictable option because it is a real relational engine, bundled on both Android and iOS, and works the same in debug and release builds.

This walkthrough is the example I hand to people who ask how to wire up local persistence without an ORM. You get a versioned schema, a small repository class, tested CRUD methods, and a migration path for the day you add a column. The numbers below are typical ranges you should expect on mid-range hardware, not benchmarks from a specific device.

Why sqflite and not something simpler

SharedPreferences is fine for a handful of flags, but it rewrites the whole file on each commit and gives you no queries, no indexes, and no transactions. SQLite handles thousands of rows without breaking a sweat, supports WHERE clauses and ORDER BY, and lets you join related tables when your data model grows up.

The sqflite plugin is a thin binding over the platform SQLite libraries, so you are not shipping a database engine yourself. Reads of a few hundred rows typically land in single-digit milliseconds. The trade-off: everything is asynchronous through a background isolate, and you write your own SQL. If you only need key-value storage, a simpler package will do.

  • Use sqflite for lists, relations, and anything you will filter or sort
  • Use key-value storage for a dozen preferences at most
  • Add sqflite_common_ffi if you want to run the same code in unit tests on desktop

Adding dependencies and opening the database

Add sqflite and path to pubspec.yaml. The path package gives you getDatabasesPath(), the platform-specific directory where databases belong. Never hardcode a path; on iOS the app container moves between installs, and a stale absolute path is a classic source of 'database not found' bugs.

Open the database lazily and keep a single reference. Opening it in main() before runApp works, but a lazy Future-backed singleton keeps cold start fast and avoids blocking the first frame. Guard the open call so two concurrent callers do not create two connections; a simple Future field is enough for that.

  • sqflite: the plugin itself
  • path: resolves a safe database directory
  • openDatabase(path, version: 1, onCreate: ...) — version drives migrations
30Batch180One-by-one (100)540One-by-one (300)900One-by-one (500)
Batch insert of 500 rows vs one-by-one inserts (ms) (ms)

Designing the schema and onCreate

For a notes example, a single table with an integer primary key, a title, a body, and a created timestamp covers most needs. Use INTEGER for timestamps stored as milliseconds since epoch; it sorts naturally and avoids string parsing. Add NOT NULL constraints early, because adding them later requires a table rebuild.

The onCreate callback runs once, so it is the right place for CREATE TABLE plus any seed data. Keep the SQL in a constant string rather than building it with interpolation, and name your columns consistently so the mapping code stays short. If your screen renders a growing list, the widget count can surprise you — see how many widgets a typical Flutter screen really uses.

  • id INTEGER PRIMARY KEY AUTOINCREMENT
  • title TEXT NOT NULL
  • body TEXT NOT NULL DEFAULT ''
  • created_at INTEGER NOT NULL
  • CREATE INDEX idx_notes_created ON notes(created_at DESC)

A small repository with CRUD methods

Wrap the raw Database in a repository class so screens never see SQL. Each method returns a typed model, and each write uses insert, update, or delete with explicit where clauses and whereArgs. Passing arguments separately avoids quoting bugs and keeps prepared statements reusable.

For bulk work, use a batch. Inserting 500 notes one await at a time can take a second or more because each call crosses the isolate boundary; a single batch usually finishes in the low tens of milliseconds. Wrap related writes in a transaction so a failure halfway does not leave half-written data.

  • insert returns the new row id
  • update and delete return the affected row count — check it
  • Use ConflictAlgorithm.replace for upserts on a unique key
  • batch.commit(noResult: true) when you do not need ids back

Migrations that will not bite you later

Ship version 1 with a clean onCreate, then bump the version number whenever the schema changes and implement onUpgrade with a switch on oldVersion. Add columns with ALTER TABLE ADD COLUMN, which is cheap and preserves data. Anything more structural — changing types, adding constraints — means creating a new table, copying rows, and dropping the old one inside a transaction.

Test the upgrade path by installing the old build, adding data, then installing the new one. That single manual test catches most migration bugs. If you also persist state in widgets, keep the state lifecycle in mind; StatelessWidget vs StatefulWidget explains when a rebuild will re-read from the database.

  • Never edit an existing onCreate after release
  • Wrap multi-step upgrades in a transaction
  • Keep a copy of the previous schema in comments or a test fixture

Performance and threading expectations

sqflite runs queries on a background thread, so the UI stays smooth, but the cost still exists. A single-row insert is usually under 2 ms; a query returning 200 rows with an index typically takes 5–15 ms on mid-range phones. Without an index on the sort column, that same query can climb into the hundreds of milliseconds once the table grows past a few thousand rows.

Paginate lists with LIMIT and OFFSET, or keyset pagination on created_at, and build widgets lazily. Opening the database the first time costs roughly 10–30 ms, which is why a lazy singleton pays off. If you are choosing between client layers for remote data alongside this local store, Retrofit vs Ktor Client covers the network side.

Typical SQLite operation timings on a mid-range Android phone (sqflite, release build)
OperationRowsTypical timeNotes
Open database (first time)—10–30 msLazy singleton recommended
Single insert11–2 msCrosses isolate boundary
Batch insert50015–40 msOne commit, noResult
Query by primary key11–3 msIndexed automatically
Query sorted, no index5,000150–400 msAdd index on sort column
Query sorted, indexed5,0008–20 msLIMIT 50 for display

Testing and common pitfalls

Use sqflite_common_ffi in tests to run the same SQL against an in-memory database. That makes repository tests fast and deterministic, and it lets you assert on migrations by opening version 1, inserting rows, then reopening at version 2. No device or emulator required, which matters in CI.

The most common mistakes are storing dates as formatted strings, forgetting to close the database in dispose for short-lived isolates, and calling setState after an await without checking mounted. Also avoid holding a Database reference across hot restart in development; the old handle can point at a closed connection.

  • Store timestamps as integers, format at the UI layer
  • Check mounted before setState after any await
  • Close test databases in tearDown
  • Log slow queries during development and add indexes

Key points

  • sqflite gives you real SQL and transactions with almost no setup cost
  • Keep a lazy singleton Database and never hardcode the file path
  • Version your schema from day one and test the upgrade path manually
  • Batch writes and index your sort columns — those two changes dominate performance

Flutter Screen Widget and Cost Estimator

Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.

Calculate

Dhrumil Patel

Editor and Flutter contributor

Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.

Related articles

Data Binding in RecyclerView: Setup and Common Pitfalls

A practical walkthrough of enabling data binding and avoiding the usual layout errors.

Flutter vs Kotlin for Android Development: A Practical Comparison

Compare Flutter and Kotlin for Android app development, covering performance, UI, code reuse, and when to choose each.

Kotlin Coroutines on Android: Common Mistakes With Numbers

Explains dispatcher choice, timeout values and cancellation patterns that avoid leaks.

Cookie preferences

Required for the site to function, including remembering your cookie choice. Always on.

Not used on this site.

Not used on this site.