gracefullight/pkgs / .agents/skills/oma-mobile
oma-mobile
UnverifiedImplement Flutter, React Native, or native Swift apps. Use for mobile screens, widgets, platform integrations, and application data flows.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 8.9 KB |
| resources/checklist.md | markdown | 3.9 KB |
| resources/error-playbook.md | markdown | 10.8 KB |
| resources/execution-protocol.md | markdown | 3.5 KB |
| resources/screen-template.dart | other | 11.0 KB |
| resources/screen-template.swift | script | 8.1 KB |
| resources/screen-template.tsx | other | 5.7 KB |
| resources/tech-stack.md | markdown | 3.8 KB |
| variants/README.md | markdown | 2.0 KB |
| variants/flutter/api-template.dart | other | 18.3 KB |
| variants/flutter/snippets.md | markdown | 41.4 KB |
| variants/flutter/stack.yaml | config | 456 B |
| variants/flutter/tech-stack.md | markdown | 11.4 KB |
| variants/react-native/api-template.ts | script | 16.3 KB |
| variants/react-native/snippets.md | markdown | 30.4 KB |
| variants/react-native/stack.yaml | config | 574 B |
| variants/react-native/tech-stack.md | markdown | 11.2 KB |
| variants/stack.schema.json | config | 2.5 KB |
| variants/swift-ios/api-template.swift | script | 6.8 KB |
| variants/swift-ios/snippets.md | markdown | 35.8 KB |
| variants/swift-ios/stack.yaml | config | 682 B |
| variants/swift-ios/tech-stack.md | markdown | 10.9 KB |
variants/flutter/snippets.md
View on GitHub# Mobile Agent - Code Snippets (Flutter)
Copy-paste ready patterns. Use these as starting points; adapt to the specific task.
Always cache decoded domain entities at the Repository layer — never at the Dio transport layer.
---
## §1. pubspec.yaml Dependencies
```yaml
# pubspec.yaml
name: my_app
description: Flutter app with Clean Architecture + Riverpod + Drift offline-first cache.
version: 1.0.0+1
environment:
sdk: ">=3.10.0 <4.0.0" # go_router 17 requires Dart >= 3.10
flutter: ">=3.44.0"
dependencies:
flutter:
sdk: flutter
# State management
flutter_riverpod: ^3.3.0
riverpod_annotation: ^4.0.0
# Navigation
go_router: ^17.3.0
# HTTP client
dio: ^5.4.3+1
pretty_dio_logger: ^1.4.0 # debug builds only; wrap in kDebugMode guard
# Local storage — offline cache (system of record for server-owned data)
drift: ^2.34.0
sqlite3_flutter_libs: ^0.5.24
path_provider: ^2.1.3
path: ^1.9.0
# Secrets
flutter_secure_storage: ^9.2.2
# Lightweight preferences
shared_preferences: ^2.3.2
# Value types / equality (optional but recommended for domain entities)
freezed_annotation: ^3.1.0
json_annotation: ^4.9.0
dev_dependencies:
flutter_test:
sdk: flutter
# Code generation
build_runner: ^2.4.11
riverpod_generator: ^4.0.0
drift_dev: ^2.34.0
go_router_builder: ^4.3.0
freezed: ^3.2.0
json_serializable: ^6.8.0
# Test mocking
mocktail: ^1.0.4
# Lint
flutter_lints: ^6.0.0
```
Run code generation after adding packages:
```bash
flutter pub get
dart run build_runner build --delete-conflicting-outputs
```
---
## §2. GoRouter with Typed Routes
```dart
// lib/core/router/app_router.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/todos/presentation/screens/todos_screen.dart';
import '../../features/todos/presentation/screens/todo_detail_screen.dart';
part 'app_router.g.dart';
// ---------------------------------------------------------------------------
// Typed route declarations — go_router_builder generates push()/go() helpers
// ---------------------------------------------------------------------------
@TypedGoRoute<TodosRoute>(
path: '/',
routes: [
TypedGoRoute<TodoDetailRoute>(path: 'todos/:id'),
],
)
class TodosRoute extends GoRouteData {
const TodosRoute();
@override
Widget build(BuildContext context, GoRouterState state) =>
const TodosScreen();
}
class TodoDetailRoute extends GoRouteData {
const TodoDetailRoute({required this.id});
final int id;
@override
Widget build(BuildContext context, GoRouterState state) =>
TodoDetailScreen(todoId: id);
}
// ---------------------------------------------------------------------------
// Router provider — singleton, lives as long as the ProviderScope
// ---------------------------------------------------------------------------
@Riverpod(keepAlive: true)
GoRouter appRouter(Ref ref) {
return GoRouter(
initialLocation: '/',
debugLogDiagnostics: true,
routes: $appRoutes, // generated list
redirect: (context, state) {
// Global auth guard example — replace with real auth state:
// final isAuthenticated = ref.read(authProvider).isAuthenticated;
// if (!isAuthenticated && state.matchedLocation != '/login') return '/login';
return null;
},
);
}
```
Usage in a screen:
```dart
// Navigate to detail:
TodoDetailRoute(id: todo.id).push(context);
// Navigate replacing current:
const TodosRoute().go(context);
```
---
## §3. Domain Entity + Repository Interface + Offline-First Implementation
### §3a. Domain Entity
```dart
// lib/features/todos/domain/todo.dart
import 'package:freezed_annotation/freezed_annotation.dart';
part 'todo.freezed.dart';
/// Pure domain entity — no Drift, no Dio, no JSON annotations.
/// Equality and copyWith are generated by freezed.
/// Freezed 3 requires the class to be `abstract` (or `sealed`).
@freezed
abstract class Todo with _$Todo {
const factory Todo({
required int id,
required String title,
required bool completed,
required DateTime cachedAt, // populated by the Repository when storing
}) = _Todo;
}
```
### §3b. Repository Interface (domain layer)
```dart
// lib/features/todos/domain/todo_repository.dart
import 'todo.dart';
/// Abstract contract the presentation layer depends on.
/// Concrete implementations (online, offline-first, stub) swap behind this seam.
abstract interface class TodoRepository {
/// Emits the cached list immediately, then re-emits after network revalidation.
/// Callers never interact with Drift or Dio directly.
Stream<List<Todo>> watchAll();
/// Returns the cached todo for [id] immediately (or null when absent),
/// revalidating from the network in the background only when it is stale.
/// A `Future` cannot re-emit — watchers of [watchAll] observe the refreshed
/// row via the Drift stream after a background revalidation completes.
Future<Todo?> findById(int id);
Future<Todo> create(String title);
Future<Todo> toggle(int id);
Future<void> delete(int id);
}
```
### §3c. Drift Table + DAO (data layer — local cache)
```dart
// lib/core/database/app_database.dart
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/todos/data/local/todos_dao.dart';
part 'app_database.g.dart';
// ---------------------------------------------------------------------------
// Todos cache table
// ---------------------------------------------------------------------------
/// One row per server-owned Todo. `cachedAt` drives TTL checks.
class TodosTable extends Table {
IntColumn get id => integer()();
TextColumn get title => text()();
BoolColumn get completed => boolean().withDefault(const Constant(false))();
DateTimeColumn get cachedAt => dateTime()();
@override
Set<Column> get primaryKey => {id};
}
@DriftDatabase(tables: [TodosTable], daos: [TodosDao])
class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
AppDatabase.forTesting(super.executor); // pass NativeDatabase.memory() in tests
@override
int get schemaVersion => 1;
}
LazyDatabase _openConnection() {
return LazyDatabase(() async {
final dir = await getApplicationDocumentsDirectory();
final file = File(p.join(dir.path, 'app.sqlite'));
return NativeDatabase.createInBackground(file);
});
}
// ---------------------------------------------------------------------------
// App-wide DB provider
// ---------------------------------------------------------------------------
@Riverpod(keepAlive: true)
AppDatabase appDatabase(Ref ref) {
final db = AppDatabase();
ref.onDispose(db.close);
return db;
}
```
```dart
// lib/features/todos/data/local/todos_dao.dart
import 'package:drift/drift.dart';
import '../../../../core/database/app_database.dart';
part 'todos_dao.g.dart';
@DriftAccessor(tables: [TodosTable])
class TodosDao extends DatabaseAccessor<AppDatabase> with _$TodosDaoMixin {
TodosDao(super.db);
/// Live stream — emits updated rows whenever Drift detects a change.
Stream<List<TodosTableData>> watchAll() => select(todosTable).watch();
/// Upsert a batch of rows (INSERT OR REPLACE). Additive only — does NOT
/// remove rows absent from [rows]. Use for seeding; use [replaceAll] to
/// mirror a full server list.
Future<void> upsertAll(List<TodosTableCompanion> rows) =>
batch((b) => b.insertAllOnConflictUpdate(todosTable, rows));
/// Replace the whole cached list with the fresh server set in ONE
/// transaction: delete rows the server no longer returns, then upsert the
/// rest. Without the delete step, server-side deletions linger as ghost
/// rows. `isNotIn([])` (empty fresh set) safely deletes all rows in Drift.
Future<void> replaceAll(List<TodosTableCompanion> rows) {
return transaction(() async {
final freshIds = rows.map((r) => r.id.value).toList();
await (delete(todosTable)..where((t) => t.id.isNotIn(freshIds))).go();
await batch((b) => b.insertAllOnConflictUpdate(todosTable, rows));
});
}
/// Upsert a single row after create/toggle.
Future<void> upsertOne(TodosTableCompanion row) =>
into(todosTable).insertOnConflictUpdate(row);
Future<void> deleteById(int id) =>
(delete(todosTable)..where((t) => t.id.equals(id))).go();
Future<TodosTableData?> findById(int id) =>
(select(todosTable)..where((t) => t.id.equals(id))).getSingleOrNull();
}
```
### §3d. Remote Data Source (data layer — Dio calls)
```dart
// lib/features/todos/data/remote/todos_remote_data_source.dart
import 'package:dio/dio.dart';
import '../dtos/todo_dto.dart';
/// All Dio calls for the /todos resource.
/// No caching here — transport concerns only.
class TodosRemoteDataSource {
TodosRemoteDataSource(this._dio);
final Dio _dio;
Future<List<TodoDto>> fetchAll() async {
final response = await _dio.get<List<dynamic>>('/todos');
return (response.data ?? [])
.map((json) => TodoDto.fromJson(json as Map<String, dynamic>))
.toList();
}
Future<TodoDto> fetchById(int id) async {
final response = await _dio.get<Map<String, dynamic>>('/todos/$id');
return TodoDto.fromJson(response.data!);
}
Future<TodoDto> create(String title) async {
final response = await _dio.post<Map<String, dynamic>>(
'/todos',
data: {'title': title},
);
return TodoDto.fromJson(response.data!);
}
Future<TodoDto> toggle(int id) async {
final response = await _dio.patch<Map<String, dynamic>>('/todos/$id/toggle');
return TodoDto.fromJson(response.data!);
}
Future<void> delete(int id) => _dio.delete<void>('/todos/$id');
}
```
```dart
// lib/features/todos/data/dtos/todo_dto.dart
import 'package:json_annotation/json_annotation.dart';
import '../../domain/todo.dart';
part 'todo_dto.g.dart';
/// JSON transfer object. Isolated from the domain entity.
@JsonSerializable()
class TodoDto {
const TodoDto({
required this.id,
required this.title,
required this.completed,
});
final int id;
final String title;
final bool completed;
factory TodoDto.fromJson(Map<String, dynamic> json) => _$TodoDtoFromJson(json);
Map<String, dynamic> toJson() => _$TodoDtoToJson(this);
/// Map to domain entity; `cachedAt` is set by the Repository, not the DTO.
Todo toDomain({required DateTime cachedAt}) => Todo(
id: id,
title: title,
completed: completed,
cachedAt: cachedAt,
);
}
```
### §3e. Offline-First Repository Implementation (data layer)
```dart
// lib/features/todos/data/todo_repository_impl.dart
import 'package:dio/dio.dart';
import 'package:drift/drift.dart';
import '../../../core/database/app_database.dart';
import '../domain/todo.dart';
import '../domain/todo_repository.dart';
import 'dtos/todo_dto.dart';
import 'local/todos_dao.dart';
import 'remote/todos_remote_data_source.dart';
/// TTL for the todos list cache. Revalidate if the newest row is older than this.
const _kCacheTtl = Duration(minutes: 5);
/// Offline-first implementation of [TodoRepository].
///
/// Caching contract:
/// - [watchAll] maps the Drift stream to domain entities and emits immediately.
/// A background revalidation triggers whenever the cache is stale (> TTL)
/// or empty. Drift re-emits the stream automatically after each upsert.
/// - Writes ([create], [toggle], [delete]) hit the network first, then upsert
/// or delete the local Drift row so the stream emits the change instantly.
/// - Cache key = logical operation, never URLs. TTL is explicit; no infinite cache.
/// - Secrets and user-authored data are NOT stored here — use flutter_secure_storage
/// or a separate Drift table with a different retention policy.
///
/// Note: staleness is evaluated at subscription time only. A long-lived
/// subscription revalidates when it is (re-)subscribed — e.g. on app
/// foreground or a `ref.invalidate` — not continuously while open. Drive
/// periodic refresh from the presentation layer (pull-to-refresh, an
/// app-lifecycle listener) if you need it while a screen stays mounted.
class TodoRepositoryImpl implements TodoRepository {
TodoRepositoryImpl({
required TodosDao dao,
required TodosRemoteDataSource remote,
}) : _dao = dao,
_remote = remote;
final TodosDao _dao;
final TodosRemoteDataSource _remote;
// ---------------------------------------------------------------------------
// READ — stale-while-revalidate
// ---------------------------------------------------------------------------
@override
Stream<List<Todo>> watchAll() async* {
// 1. Emit cached rows immediately (may be empty on first run).
final initial = await _dao.watchAll().first;
final now = DateTime.now();
// 2. Determine whether revalidation is needed.
final isStale = initial.isEmpty ||
initial.any((row) => now.difference(row.cachedAt) > _kCacheTtl);
if (isStale) {
// 3. Fetch from network in the background and upsert into Drift.
// Drift's stream will re-emit automatically after the upsert.
_revalidate().ignore();
}
// 4. Forward the live Drift stream (emits on every upsert from step 3 onward).
yield* _dao.watchAll().map(
(rows) => rows.map(_rowToEntity).toList(),
);
}
@override
Future<Todo?> findById(int id) async {
final cached = await _dao.findById(id);
final now = DateTime.now();
if (cached != null) {
// Serve the cached row immediately. Revalidate in the background only
// when it is stale; watchers of watchAll() pick up the refreshed row via
// the Drift stream. This Future returns the cached snapshot as-is.
if (now.difference(cached.cachedAt) > _kCacheTtl) {
_revalidateById(id, now).ignore();
}
return _rowToEntity(cached);
}
// Cache miss — fetch from network and persist.
try {
final dto = await _remote.fetchById(id);
await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
return dto.toDomain(cachedAt: now);
} on DioException catch (e) {
if (e.response?.statusCode == 404) return null;
rethrow;
}
}
Future<void> _revalidate() async {
try {
final dtos = await _remote.fetchAll();
final now = DateTime.now();
// replaceAll (not upsertAll): mirror the full server list so rows the
// server deleted are removed instead of lingering as ghost rows.
await _dao.replaceAll(
dtos.map((dto) => _dtoToCompanion(dto, cachedAt: now)).toList(),
);
} catch (_) {
// Network failure is non-fatal when the cache is warm.
// The existing stream emission (stale data) stands.
}
}
Future<void> _revalidateById(int id, DateTime now) async {
try {
final dto = await _remote.fetchById(id);
await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
} catch (_) {
// Non-fatal — caller already received the cached value.
}
}
// ---------------------------------------------------------------------------
// WRITE — invalidate/update cache after success
// ---------------------------------------------------------------------------
@override
Future<Todo> create(String title) async {
final dto = await _remote.create(title);
final now = DateTime.now();
// Upsert the new row so watchAll() emits without waiting for a revalidation.
await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
return dto.toDomain(cachedAt: now);
}
@override
Future<Todo> toggle(int id) async {
final dto = await _remote.toggle(id);
final now = DateTime.now();
await _dao.upsertOne(_dtoToCompanion(dto, cachedAt: now));
return dto.toDomain(cachedAt: now);
}
@override
Future<void> delete(int id) async {
await _remote.delete(id);
// Remove the row so the stream emits the deletion immediately.
await _dao.deleteById(id);
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
Todo _rowToEntity(TodosTableData row) => Todo(
id: row.id,
title: row.title,
completed: row.completed,
cachedAt: row.cachedAt,
);
TodosTableCompanion _dtoToCompanion(TodoDto dto, {required DateTime cachedAt}) =>
TodosTableCompanion(
id: Value(dto.id),
title: Value(dto.title),
completed: Value(dto.completed),
cachedAt: Value(cachedAt),
);
}
```
---
## §4. Riverpod StreamNotifier Consuming the Repository Stream
```dart
// lib/features/todos/presentation/providers/todos_provider.dart
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/todo.dart';
import '../../domain/todo_repository.dart';
import '../../../../core/di/providers.dart'; // todoRepositoryProvider
part 'todos_provider.g.dart';
/// Exposes the offline-first todo list.
///
/// Riverpod converts the Repository's Stream into AsyncValue<List<Todo>>.
/// The UI receives AsyncValue.loading() on first subscription, then
/// AsyncValue.data(cachedList) on the first Drift emission, then
/// AsyncValue.data(freshList) after network revalidation — without any
/// loading flicker if the cache is warm.
@riverpod
class TodosNotifier extends _$TodosNotifier {
@override
Stream<List<Todo>> build() {
final repo = ref.watch(todoRepositoryProvider);
return repo.watchAll();
}
Future<void> create(String title) async {
final repo = ref.read(todoRepositoryProvider);
await repo.create(title);
// Stream auto-updates via Drift; no manual state mutation needed.
}
Future<void> toggle(int id) async {
final repo = ref.read(todoRepositoryProvider);
await repo.toggle(id);
}
Future<void> delete(int id) async {
final repo = ref.read(todoRepositoryProvider);
await repo.delete(id);
}
}
```
```dart
// lib/core/di/providers.dart
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../database/app_database.dart';
import '../network/dio_client.dart';
import '../../features/todos/data/local/todos_dao.dart';
import '../../features/todos/data/remote/todos_remote_data_source.dart';
import '../../features/todos/data/todo_repository_impl.dart';
import '../../features/todos/domain/todo_repository.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
Dio dio(Ref ref) => buildDioClient(ref);
@Riverpod(keepAlive: true)
TodosDao todosDao(Ref ref) {
final db = ref.watch(appDatabaseProvider);
return db.todosDao;
}
@Riverpod(keepAlive: true)
TodosRemoteDataSource todosRemoteDataSource(Ref ref) =>
TodosRemoteDataSource(ref.watch(dioProvider));
@Riverpod(keepAlive: true)
TodoRepository todoRepository(Ref ref) => TodoRepositoryImpl(
dao: ref.watch(todosDaoProvider),
remote: ref.watch(todosRemoteDataSourceProvider),
);
```
---
## §5. Dio Client with Auth + Retry + Logging Interceptors
```dart
// lib/core/network/dio_client.dart
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
/// Builds the app-wide Dio instance with interceptors.
/// Called once from the DI layer; never instantiated in features directly.
Dio buildDioClient(Ref ref) {
final dio = Dio(
BaseOptions(
baseUrl: const String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://api.example.com',
),
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 30),
headers: {'Content-Type': 'application/json'},
),
);
// Transport-layer interceptors only — no caching here.
dio.interceptors.addAll([
AuthInterceptor(const FlutterSecureStorage()),
RetryInterceptor(dio),
if (kDebugMode) PrettyDioLogger(requestBody: true, responseBody: true),
]);
return dio;
}
// ---------------------------------------------------------------------------
// Auth interceptor — injects Bearer token from secure storage
// ---------------------------------------------------------------------------
class AuthInterceptor extends Interceptor {
AuthInterceptor(this._storage);
final FlutterSecureStorage _storage;
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
final token = await _storage.read(key: 'access_token');
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
if (err.response?.statusCode == 401) {
// TODO: trigger token refresh or sign-out flow via ref
// For now, pass the error through to the caller.
}
handler.next(err);
}
}
// ---------------------------------------------------------------------------
// Retry interceptor — exponential back-off on transient failures
// ---------------------------------------------------------------------------
class RetryInterceptor extends Interceptor {
RetryInterceptor(this._dio, {this.maxRetries = 3});
final Dio _dio;
final int maxRetries;
@override
Future<void> onError(
DioException err,
ErrorInterceptorHandler handler,
) async {
final attempt = err.requestOptions.extra['_retryCount'] as int? ?? 0;
// Only retry idempotent methods. Retrying a POST on receiveTimeout can
// duplicate a non-idempotent write (the server may have applied the first
// request before the response timed out).
const idempotentMethods = {'GET', 'HEAD', 'PUT', 'DELETE'};
final isIdempotent =
idempotentMethods.contains(err.requestOptions.method.toUpperCase());
final isRetriable = isIdempotent &&
(err.type == DioExceptionType.connectionTimeout ||
err.type == DioExceptionType.receiveTimeout ||
err.type == DioExceptionType.connectionError);
if (isRetriable && attempt < maxRetries) {
await Future.delayed(Duration(milliseconds: 200 * (1 << attempt)));
try {
final opts = err.requestOptions
..extra['_retryCount'] = attempt + 1;
final response = await _dio.fetch<dynamic>(opts);
handler.resolve(response);
return;
} catch (_) {
// Fall through to next handler on retry failure.
}
}
handler.next(err);
}
}
```
---
## §6. Todos Screen (ConsumerStatefulWidget)
```dart
// lib/features/todos/presentation/screens/todos_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/todo.dart';
import '../providers/todos_provider.dart';
import '../widgets/todo_list_item.dart';
import '../../../../shared/widgets/empty_state.dart';
import '../../../../shared/widgets/error_view.dart';
class TodosScreen extends ConsumerStatefulWidget {
const TodosScreen({super.key});
@override
ConsumerState<TodosScreen> createState() => _TodosScreenState();
}
class _TodosScreenState extends ConsumerState<TodosScreen> {
final _titleController = TextEditingController();
@override
void dispose() {
_titleController.dispose(); // always dispose controllers
super.dispose();
}
@override
Widget build(BuildContext context) {
final todosAsync = ref.watch(todosNotifierProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Todos'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Refresh',
// Invalidate causes build() to re-subscribe to watchAll()
// which triggers a fresh revalidation cycle.
onPressed: () => ref.invalidate(todosNotifierProvider),
),
],
),
body: todosAsync.when(
// Warm cache is available — render immediately, no spinner.
// Riverpod passes skipLoadingOnRefresh: true by default in Riverpod 3.x
// so a background revalidation does not re-show the loading state.
data: (todos) => todos.isEmpty
? const EmptyState(
icon: Icons.check_circle_outline,
title: 'No todos yet',
subtitle: 'Add your first todo below.',
)
: _TodoList(todos: todos),
loading: () => const Center(child: CircularProgressIndicator()),
error: (err, _) => ErrorView(
message: err.toString(),
onRetry: () => ref.invalidate(todosNotifierProvider),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _showAddDialog,
tooltip: 'Add todo',
child: const Icon(Icons.add),
),
);
}
void _showAddDialog() {
_titleController.clear();
showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('New Todo'),
content: TextField(
controller: _titleController,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Title',
hintText: 'What needs to be done?',
),
onSubmitted: (_) => _submitAdd(ctx),
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => _submitAdd(ctx),
child: const Text('Add'),
),
],
),
);
}
Future<void> _submitAdd(BuildContext dialogCtx) async {
final title = _titleController.text.trim();
if (title.isEmpty) return;
Navigator.of(dialogCtx).pop();
await ref.read(todosNotifierProvider.notifier).create(title);
}
}
// ---------------------------------------------------------------------------
// Internal list widget
// ---------------------------------------------------------------------------
class _TodoList extends ConsumerWidget {
const _TodoList({required this.todos});
final List<Todo> todos;
@override
Widget build(BuildContext context, WidgetRef ref) {
return RefreshIndicator(
// Pull-to-refresh forces a full revalidation cycle. Await the next
// stream value via `.future` so the spinner stays until fresh data
// arrives — `ref.invalidate` returns synchronously and dismisses early.
onRefresh: () => ref.refresh(todosNotifierProvider.future),
child: ListView.builder(
itemCount: todos.length,
itemBuilder: (ctx, i) => TodoListItem(
todo: todos[i],
onToggle: () =>
ref.read(todosNotifierProvider.notifier).toggle(todos[i].id),
onDelete: () =>
ref.read(todosNotifierProvider.notifier).delete(todos[i].id),
),
),
);
}
}
```
---
## §7. Shared Widgets (EmptyState, ErrorView, TodoListItem)
```dart
// lib/shared/widgets/empty_state.dart
import 'package:flutter/material.dart';
class EmptyState extends StatelessWidget {
const EmptyState({
super.key,
required this.icon,
required this.title,
this.subtitle,
});
final IconData icon;
final String title;
final String? subtitle;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 64, color: theme.colorScheme.secondary),
const SizedBox(height: 16),
Text(title, style: theme.textTheme.titleLarge),
if (subtitle != null) ...[
const SizedBox(height: 8),
Text(
subtitle!,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
),
textAlign: TextAlign.center,
),
],
],
),
),
);
}
}
```
```dart
// lib/shared/widgets/error_view.dart
import 'package:flutter/material.dart';
class ErrorView extends StatelessWidget {
const ErrorView({super.key, required this.message, this.onRetry});
final String message;
final VoidCallback? onRetry;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.error_outline, size: 64, color: theme.colorScheme.error),
const SizedBox(height: 16),
Text(
'Something went wrong',
style: theme.textTheme.titleLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
message,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
),
textAlign: TextAlign.center,
),
if (onRetry != null) ...[
const SizedBox(height: 24),
FilledButton.icon(
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: const Text('Try Again'),
),
],
],
),
),
);
}
}
```
```dart
// lib/features/todos/presentation/widgets/todo_list_item.dart
import 'package:flutter/material.dart';
import '../../domain/todo.dart';
class TodoListItem extends StatelessWidget {
const TodoListItem({
super.key,
required this.todo,
required this.onToggle,
required this.onDelete,
});
final Todo todo;
final VoidCallback onToggle;
final VoidCallback onDelete;
@override
Widget build(BuildContext context) {
return ListTile(
leading: Checkbox(
value: todo.completed,
onChanged: (_) => onToggle(),
),
title: Text(
todo.title,
style: todo.completed
? TextStyle(
decoration: TextDecoration.lineThrough,
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
)
: null,
),
trailing: IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: 'Delete',
onPressed: onDelete,
),
);
}
}
```
---
## §8. App Entry Point (main.dart)
```dart
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'core/router/app_router.dart';
import 'core/theme/app_theme.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
// ProviderScope is the Riverpod root — must wrap the entire widget tree.
const ProviderScope(child: MyApp()),
);
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(appRouterProvider);
return MaterialApp.router(
title: 'My App',
theme: AppTheme.light(),
darkTheme: AppTheme.dark(),
routerConfig: router,
debugShowCheckedModeBanner: false,
);
}
}
```
```dart
// lib/core/theme/app_theme.dart
import 'package:flutter/material.dart';
/// Material 3 light/dark themes seeded from a single brand color.
/// Kept intentionally small — extend with typography/component themes per project.
abstract final class AppTheme {
static const _seed = Color(0xFF1A2332); // Deep Ocean Navy
static ThemeData light() => _base(Brightness.light);
static ThemeData dark() => _base(Brightness.dark);
static ThemeData _base(Brightness brightness) {
final scheme = ColorScheme.fromSeed(
seedColor: _seed,
brightness: brightness,
);
return ThemeData(
useMaterial3: true,
colorScheme: scheme,
scaffoldBackgroundColor: scheme.surface,
appBarTheme: AppBarTheme(
backgroundColor: scheme.surface,
foregroundColor: scheme.onSurface,
centerTitle: false,
),
);
}
}
```
---
## §9. flutter_test + mocktail Unit Tests
```dart
// test/features/todos/todos_provider_test.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:my_app/features/todos/domain/todo.dart';
import 'package:my_app/features/todos/domain/todo_repository.dart';
import 'package:my_app/features/todos/presentation/providers/todos_provider.dart';
import 'package:my_app/core/di/providers.dart';
// ---------------------------------------------------------------------------
// Mock — depends on the abstract repository interface, not the Dio/Drift impl
// ---------------------------------------------------------------------------
class MockTodoRepository extends Mock implements TodoRepository {}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
final _now = DateTime(2025, 1, 1);
Todo _makeTodo(int id, {bool completed = false}) => Todo(
id: id,
title: 'Todo $id',
completed: completed,
cachedAt: _now,
);
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
void main() {
late MockTodoRepository mockRepo;
late ProviderContainer container;
setUp(() {
mockRepo = MockTodoRepository();
container = ProviderContainer(
overrides: [
// Swap the real repository for the mock at the DI seam.
todoRepositoryProvider.overrideWithValue(mockRepo),
],
);
addTearDown(container.dispose);
});
test('todosNotifierProvider emits data from repository stream', () async {
final todos = [_makeTodo(1), _makeTodo(2)];
when(() => mockRepo.watchAll()).thenAnswer(
(_) => Stream.value(todos),
);
// Wait for the async stream to emit.
final result = await container
.read(todosNotifierProvider.future);
expect(result, equals(todos));
});
test('todosNotifierProvider emits empty list when repository returns []', () async {
when(() => mockRepo.watchAll()).thenAnswer((_) => Stream.value([]));
final result = await container.read(todosNotifierProvider.future);
expect(result, isEmpty);
});
test('todosNotifierProvider propagates repository errors', () async {
when(() => mockRepo.watchAll())
.thenAnswer((_) => Stream.error(Exception('network error')));
await expectLater(
container.read(todosNotifierProvider.future),
throwsA(isA<Exception>()),
);
});
test('create calls repository and stream auto-updates', () async {
final initial = [_makeTodo(1)];
final afterCreate = [_makeTodo(1), _makeTodo(2, completed: false)];
var streamIndex = 0;
final streams = [Stream.value(initial), Stream.value(afterCreate)];
when(() => mockRepo.watchAll())
.thenAnswer((_) => streams[streamIndex++ % streams.length]);
when(() => mockRepo.create(any()))
.thenAnswer((_) async => _makeTodo(2));
await container.read(todosNotifierProvider.notifier).create('Todo 2');
verify(() => mockRepo.create('Todo 2')).called(1);
});
}
```
```dart
// test/features/todos/todo_repository_impl_test.dart
// Tests the real TodoRepositoryImpl with an in-memory Drift database.
import 'dart:async';
import 'package:drift/drift.dart' show Value; // Value: drift/native.dart does not export it
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:my_app/core/database/app_database.dart';
import 'package:my_app/features/todos/data/dtos/todo_dto.dart';
import 'package:my_app/features/todos/data/local/todos_dao.dart';
import 'package:my_app/features/todos/data/remote/todos_remote_data_source.dart';
import 'package:my_app/features/todos/data/todo_repository_impl.dart';
class MockTodosRemoteDataSource extends Mock implements TodosRemoteDataSource {}
void main() {
late AppDatabase db;
late TodosDao dao;
late MockTodosRemoteDataSource mockRemote;
late TodoRepositoryImpl repo;
setUp(() {
db = AppDatabase.forTesting(NativeDatabase.memory());
dao = db.todosDao;
mockRemote = MockTodosRemoteDataSource();
repo = TodoRepositoryImpl(dao: dao, remote: mockRemote);
});
tearDown(() => db.close());
test('watchAll emits cached rows immediately then revalidates', () async {
final now = DateTime.now();
// Pre-populate the cache with a stale entry.
// `.insert()` takes RAW values for required columns (id, title, cachedAt)
// and Value() only for defaulted/nullable ones (completed).
await dao.upsertAll([
TodosTableCompanion.insert(
id: 1,
title: 'Cached todo',
cachedAt: now.subtract(const Duration(hours: 1)), // older than TTL
completed: const Value(false),
),
]);
// Gate the remote fetch behind a Completer so revalidation cannot race
// ahead of the first (cached) emission. Without the gate, if the upsert
// lands before the stream is subscribed, both emissions coalesce into one
// and `.take(2)` hangs. The test releases the gate after emission #1,
// guaranteeing two distinct emissions deterministically.
final gate = Completer<void>();
final freshDtos = [
TodoDto(id: 1, title: 'Fresh todo', completed: false),
];
when(() => mockRemote.fetchAll()).thenAnswer((_) async {
await gate.future;
return freshDtos;
});
final emissions = <int>[];
await for (final todos in repo.watchAll().take(2)) {
emissions.add(todos.length);
if (emissions.length == 1) {
gate.complete(); // cached emission seen — now let revalidation run
}
}
// First emission: cached row; second: after revalidation.
expect(emissions, [1, 1]);
verify(() => mockRemote.fetchAll()).called(1);
});
test('create upserts into Drift and stream emits new item', () async {
when(() => mockRemote.create(any()))
.thenAnswer((_) async => TodoDto(id: 99, title: 'New', completed: false));
await repo.create('New');
final rows = await dao.watchAll().first;
expect(rows.any((r) => r.id == 99), isTrue);
});
test('delete removes row from Drift after remote success', () async {
final now = DateTime.now();
await dao.upsertAll([
TodosTableCompanion.insert(
id: 5,
title: 'To delete',
cachedAt: now,
completed: const Value(false),
),
]);
when(() => mockRemote.delete(5)).thenAnswer((_) async {});
await repo.delete(5);
final rows = await dao.watchAll().first;
expect(rows.any((r) => r.id == 5), isFalse);
});
}
```
---
## §10. Cache Rules Recap
> These rules are mandatory. Violating any of them is a defect, not a style choice.
1. **Repository layer, not transport.** Cache decoded `Todo` domain entities inside `TodoRepositoryImpl`. Do NOT use a Dio interceptor (e.g. `dio_http_cache`, `dio_cache_interceptor`) as the system of record for domain reads — interceptors operate on raw bytes and are invisible to the domain and its tests.
2. **Stale-while-revalidate.** `watchAll()` emits the locally-cached Drift rows immediately (zero latency for the user), then silently revalidates from the network and re-emits via the Drift stream. No loading spinner on cache hits.
3. **Explicit TTL.** Every cache row stores `cachedAt`. The Repository compares it against `_kCacheTtl` to decide whether to revalidate. Never use an implicit or infinite TTL.
4. **Key = operation + params, never URLs.** The Drift table primary key (`id`) and the DAO operation name (e.g., `watchAll`, `findById`) are the effective cache keys. Changing the backend URL does not invalidate the cache; only writing new data or deleting rows does.
5. **Invalidate on write.** `create` → upsert new row. `toggle` → upsert updated row. `delete` → delete row. After each mutation the Drift stream emits the new state to all active subscribers without any explicit refresh call in the UI.
6. **Boundaries.** The Drift cache table is for transient server-owned data. Durable user-authored data (drafts, settings) → separate Drift table with its own retention policy. Secrets (tokens) → `flutter_secure_storage`. Do not use the cache table as a system of record.
---
## §11. Maestro E2E Flow
<!-- oma-docs:ignore-start -->
End-to-end UI test driven by Maestro. Lives at `maestro/todos_flow.yaml` (project
root, see tech-stack `Testing`). Run with `maestro test maestro/todos_flow.yaml`.
<!-- oma-docs:ignore-end -->
```yaml
# maestro/todos_flow.yaml
# Launch → assert list screen → add a todo → assert it appears.
appId: com.example.my_app
---
- launchApp:
clearState: true
- assertVisible: "Todos" # AppBar title confirms the list screen loaded
- tapOn:
id: "add" # FloatingActionButton tooltip/semantics label
- assertVisible: "New Todo" # add dialog opened
- tapOn: "Title" # focus the text field
- inputText: "Buy milk"
- tapOn: "Add" # FilledButton submits the dialog
- assertVisible: "Buy milk" # new item rendered in the list
```
> Widgets expose stable `id`s to Maestro via `Semantics(identifier: ...)` or the
> tooltip/label text shown above. Keep these labels in sync with §6 so the flow
> stays green.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |