FlutterIntermediate 2 min read

Flutter SQLite: data modeling and parameterized queries

Model persistent records with stable IDs, parameterize SQL and hide database access behind a repository contract.

On this page

SQLite is useful when local data needs relationships, constraints and queries. Choose a Flutter database package after checking the target platforms and the behavior you need, such as transactions or reactive updates.

Design the record before the screen

A task needs a stable ID, a title and a completion state. The widget should not construct SQL statements from user input. A repository can expose operations such as addTask and listTasks while hiding table details.

The fragment below assumes an opened database from a compatible SQLite package. Migration and openDatabase configuration belong in the data layer.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

await database.insert('tasks', {
  'id': taskId,
  'title': title,
  'completed': 0,
});

final rows = await database.query('tasks',
  where: 'completed = ?', whereArgs: [0], orderBy: 'title ASC');

Read the result

The placeholder separates the query structure from values. Use transactions when multiple writes must succeed together. Schema changes need a migration plan; deleting user data is not a substitute for migration.

Move from row storage to feature operations

The interface should ask to add or complete a task, not assemble SQL in a button callback. A repository can translate those operations into parameterized queries and turn stored rows into typed models.

A stable primary key identifies the record even when the list order changes. Use a transaction when several writes form one logical operation; otherwise a partial failure can leave records in a state the interface was never designed to show.

Test a database that already contains user records when changing the schema. A fresh-install test cannot prove migration preserves existing data. The repository boundary guide helps keep that behavior testable without coupling every widget to the database package.

Practice and verification

Define a unique ID constraint, add two tasks and query only incomplete records. Test an upgrade from an older schema with existing data, not only a fresh installation.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.