A shopping list app sounds trivial until you picture the user standing in the supermarket aisle, no signal, with the app stuck on an endless spinner. Offline-first isn't a feature — it's an architectural decision that has to be made before writing the first line of code. In this article I explain how I implemented this approach in Lista da Casa using Flutter and Drift.
Why Drift instead of SharedPreferences or Hive?
For simple data (app theme, last screen visited, preferences), SharedPreferences gets the job done. For serialized objects with no relations, Hive is fast and easy. But when you need to:
- Filter items by category
- Sort by name or date added
- Count how many items are still unchecked
- Handle multiple lists with related items
...you need SQL. Drift (formerly known as Moor) is a type-safe layer on top
of SQLite that runs natively on Android and iOS. You define tables as Dart classes, write
queries with compile-time verification, and get reactive Streams automatically.
No SQL in strings, no runtime errors from a typo in a column name.
Setting up Drift in the project
Add the dependencies to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
drift: ^2.16.0
sqlite3_flutter_libs: ^0.5.24
path_provider: ^2.1.3
path: ^1.9.0
dev_dependencies:
drift_dev: ^2.16.0
build_runner: ^2.4.9
sqlite3_flutter_libs includes the SQLite binary compiled for Android and iOS.
build_runner together with drift_dev is used to generate the
boilerplate code from the table definitions.
Defining the items table
// lib/data/database/tables/itens_compra.dart
import 'package:drift/drift.dart';
class ItensCompra extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get nome => text().withLength(min: 1, max: 100)();
TextColumn get categoria => text().nullable()();
BoolColumn get comprado =>
boolean().withDefault(const Constant(false))();
DateTimeColumn get criadoEm =>
dateTime().withDefault(currentDateAndTime)();
}
Each field is a typed column. autoIncrement() creates the primary key
automatically. nullable() indicates the category is optional. Drift generates
strongly typed getters and setters from this definition.
Creating the database
// lib/data/database/app_database.dart
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
part 'app_database.g.dart'; // generated by build_runner
@DriftDatabase(tables: [ItensCompra])
class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
@override
int get schemaVersion => 1;
// Returns a Stream that re-emits whenever the table changes
Stream<List<ItemCompra>> watchItens() =>
select(itensCompra).watch();
Future<int> inserirItem(ItensCompraCompanion item) =>
into(itensCompra).insert(item);
Future<void> marcarComprado(int id, bool comprado) =>
(update(itensCompra)..where((t) => t.id.equals(id)))
.write(ItensCompraCompanion(comprado: Value(comprado)));
Future<int> deletarItem(int id) =>
(delete(itensCompra)..where((t) => t.id.equals(id))).go();
}
LazyDatabase _openConnection() {
return LazyDatabase(() async {
final dir = await getApplicationDocumentsDirectory();
final file = File(p.join(dir.path, 'lista_da_casa.sqlite'));
return NativeDatabase(file);
});
}
After creating the file, run dart run build_runner build to generate
app_database.g.dart with all the SQL code under the hood.
Integrating with Riverpod
The database is instantiated once via a Provider and shared across the whole app:
// lib/providers/database_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
final dbProvider = Provider<AppDatabase>(
(ref) => AppDatabase(),
// Closes the connection when the provider is disposed
onDispose: (db) => db.close(),
);
// Stream of all items — updates the UI automatically
final itensProvider = StreamProvider<List<ItemCompra>>(
(ref) => ref.watch(dbProvider).watchItens(),
);
On the main screen, StreamProvider handles all the reactivity:
class ListaScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final itensAsync = ref.watch(itensProvider);
return itensAsync.when(
data: (itens) => ListView.builder(
itemCount: itens.length,
itemBuilder: (_, i) => ItemTile(item: itens[i]),
),
loading: () => const CircularProgressIndicator(),
error: (e, _) => Text('Erro: $e'),
);
}
}
When the user marks an item as purchased, Drift updates the database, the Stream
emits the new data, and Riverpod rebuilds the widget automatically. No
setState, no notifyListeners, no manual state management.
The result: truly offline UX
The app opens instantly — no splash screen waiting on a connection, no data lost between sessions, no "no internet" message. The local SQLite database is the source of truth. If the user stays offline for days, the data is still there, intact.
For apps that need to sync with the cloud in the future, the same SQLite database can serve as the local cache layer while Firestore acts as the remote backend — a pattern known as local-first sync.
Drift has an initial learning curve because of build_runner and code generation.
But once the project is set up, writing queries and migrations is safe, predictable, and far
more pleasant than concatenating SQL strings. It's worth the investment.
Check out Lista da Casa, available for free on Google Play:
Download Lista da Casa