Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn SQLite with Drift | Local Storage
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Flutter State and Data Handling

bookSQLite with Drift

Note
Definition

SQLite is a lightweight, embedded database engine that is widely used for managing structured data directly on a device.

In Flutter, using SQLite directly can be verbose and error-prone, especially when handling data models and queries. Drift is an Object-Relational Mapping (ORM) library for Dart that simplifies working with SQLite by providing type-safe APIs, automatic code generation, and support for reactive data streams. By using Drift, you can define your database tables as Dart classes, write queries in a more natural way, and react to changes in your data efficiently.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738394041
// main.dart import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; // Define a table class Todos extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text()(); BoolColumn get completed => boolean().withDefault(const Constant(false))(); } // Create a database class @DriftDatabase(tables: [Todos]) class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override int get schemaVersion => 1; } // Open the database connection LazyDatabase _openConnection() { return LazyDatabase(() async { final dbFolder = await getApplicationDocumentsDirectory(); final file = File(p.join(dbFolder.path, 'db.sqlite')); return NativeDatabase(file); }); } // Example usage: insert a todo Future<void> main() async { final db = AppDatabase(); final id = await db.into(db.todos).insert( TodosCompanion.insert(title: 'Learn Drift ORM'), ); print('Inserted todo with id: $id'); await db.close(); }

With Drift, querying the database becomes type-safe and concise. You can easily fetch records using generated APIs, and Drift supports reactive streams, so your UI can automatically update when the underlying data changes. For example, you can watch a table or a specific query and rebuild widgets in response to updates, making state management with local databases straightforward and robust.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142
import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; class Todos extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text()(); BoolColumn get completed => boolean().withDefault(const Constant(false))(); } @DriftDatabase(tables: [Todos]) class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override int get schemaVersion => 1; } LazyDatabase _openConnection() { return LazyDatabase(() async { final dbFolder = await getApplicationDocumentsDirectory(); final file = File(p.join(dbFolder.path, 'db.sqlite')); return NativeDatabase(file); }); } // Example usage: update a todo Future<void> main() async { final db = AppDatabase(); // Insert a todo first final id = await db.into(db.todos).insert( TodosCompanion.insert(title: 'Update Drift record'), ); // Update the todo's completed status await (db.update(db.todos)..where((t) => t.id.equals(id))).write( TodosCompanion(completed: Value(true)), ); print('Updated todo with id: $id'); await db.close(); }
question mark

Which of the following is an advantage of using Drift for local databases in Flutter?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you show me an example of how to define a table using Drift in Flutter?

How do I set up Drift in my Flutter project?

What are the main benefits of using Drift over raw SQLite in Flutter?

bookSQLite with Drift

Swipe to show menu

Note
Definition

SQLite is a lightweight, embedded database engine that is widely used for managing structured data directly on a device.

In Flutter, using SQLite directly can be verbose and error-prone, especially when handling data models and queries. Drift is an Object-Relational Mapping (ORM) library for Dart that simplifies working with SQLite by providing type-safe APIs, automatic code generation, and support for reactive data streams. By using Drift, you can define your database tables as Dart classes, write queries in a more natural way, and react to changes in your data efficiently.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738394041
// main.dart import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; // Define a table class Todos extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text()(); BoolColumn get completed => boolean().withDefault(const Constant(false))(); } // Create a database class @DriftDatabase(tables: [Todos]) class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override int get schemaVersion => 1; } // Open the database connection LazyDatabase _openConnection() { return LazyDatabase(() async { final dbFolder = await getApplicationDocumentsDirectory(); final file = File(p.join(dbFolder.path, 'db.sqlite')); return NativeDatabase(file); }); } // Example usage: insert a todo Future<void> main() async { final db = AppDatabase(); final id = await db.into(db.todos).insert( TodosCompanion.insert(title: 'Learn Drift ORM'), ); print('Inserted todo with id: $id'); await db.close(); }

With Drift, querying the database becomes type-safe and concise. You can easily fetch records using generated APIs, and Drift supports reactive streams, so your UI can automatically update when the underlying data changes. For example, you can watch a table or a specific query and rebuild widgets in response to updates, making state management with local databases straightforward and robust.

main.dart

main.dart

copy
123456789101112131415161718192021222324252627282930313233343536373839404142
import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; class Todos extends Table { IntColumn get id => integer().autoIncrement()(); TextColumn get title => text()(); BoolColumn get completed => boolean().withDefault(const Constant(false))(); } @DriftDatabase(tables: [Todos]) class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override int get schemaVersion => 1; } LazyDatabase _openConnection() { return LazyDatabase(() async { final dbFolder = await getApplicationDocumentsDirectory(); final file = File(p.join(dbFolder.path, 'db.sqlite')); return NativeDatabase(file); }); } // Example usage: update a todo Future<void> main() async { final db = AppDatabase(); // Insert a todo first final id = await db.into(db.todos).insert( TodosCompanion.insert(title: 'Update Drift record'), ); // Update the todo's completed status await (db.update(db.todos)..where((t) => t.id.equals(id))).write( TodosCompanion(completed: Value(true)), ); print('Updated todo with id: $id'); await db.close(); }
question mark

Which of the following is an advantage of using Drift for local databases in Flutter?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
some-alt