feat: Riverpod providers + GoRouter + AppShell (with generated code)

This commit is contained in:
TrochtaOndrej
2026-03-18 04:40:55 +01:00
parent 03e1ab1d24
commit d44230b455
18 changed files with 621 additions and 134 deletions
View File
+68
View File
@@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/tasks/screens/tasks_screen.dart';
import '../../features/tasks/screens/pet_screen.dart';
import '../../features/zen_mode/screens/zen_screen.dart';
import '../../shared/widgets/profile_screen.dart';
import '../../shared/widgets/app_shell.dart';
part 'app_router.g.dart';
/// Route name constants.
abstract final class Routes {
static const String tasks = '/tasks';
static const String pet = '/pet';
static const String zen = '/zen';
static const String profile = '/profile';
static const String onboarding = '/onboarding';
static const String addTask = '/add-task';
}
final _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final _shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell');
@riverpod
GoRouter appRouter(Ref ref) {
return GoRouter(
navigatorKey: _rootNavigatorKey,
initialLocation: Routes.tasks,
routes: [
ShellRoute(
navigatorKey: _shellNavigatorKey,
builder: (context, state, child) => AppShell(child: child),
routes: [
GoRoute(
path: Routes.tasks,
name: 'tasks',
pageBuilder: (context, state) => const NoTransitionPage(
child: TasksScreen(),
),
),
GoRoute(
path: Routes.pet,
name: 'pet',
pageBuilder: (context, state) => const NoTransitionPage(
child: PetScreen(),
),
),
GoRoute(
path: Routes.zen,
name: 'zen',
pageBuilder: (context, state) => const NoTransitionPage(
child: ZenScreen(),
),
),
GoRoute(
path: Routes.profile,
name: 'profile',
pageBuilder: (context, state) => const NoTransitionPage(
child: ProfileScreen(),
),
),
],
),
],
);
}
+51
View File
@@ -0,0 +1,51 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'app_router.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(appRouter)
final appRouterProvider = AppRouterProvider._();
final class AppRouterProvider
extends $FunctionalProvider<GoRouter, GoRouter, GoRouter>
with $Provider<GoRouter> {
AppRouterProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'appRouterProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$appRouterHash();
@$internal
@override
$ProviderElement<GoRouter> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
GoRouter create(Ref ref) {
return appRouter(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GoRouter value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GoRouter>(value),
);
}
}
String _$appRouterHash() => r'992c1f48b4899faf26807c2d6009807a91a03f5c';
@@ -0,0 +1,34 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'pet_providers.g.dart';
// TODO: Replace with actual Drift pet_state table once data layer is implemented.
/// Pet mood derived from pet state.
enum PetMood { happy, neutral, sad }
/// Manages the pet state (energy, streak, total tasks done).
@riverpod
class PetState extends _$PetState {
@override
Future<Map<String, dynamic>> build() async {
// TODO: Fetch from pet repository.
return {
'energyToday': 2,
'streakDays': 0,
'totalTasksDone': 0,
};
}
}
/// Derived provider for the pet's current mood.
@riverpod
Future<PetMood> petMood(Ref ref) async {
final state = await ref.watch(petStateProvider.future);
final totalDone = state['totalTasksDone'] as int? ?? 0;
final streak = state['streakDays'] as int? ?? 0;
if (streak >= 3 || totalDone >= 5) return PetMood.happy;
if (totalDone == 0) return PetMood.sad;
return PetMood.neutral;
}
@@ -0,0 +1,95 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'pet_providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Manages the pet state (energy, streak, total tasks done).
@ProviderFor(PetState)
final petStateProvider = PetStateProvider._();
/// Manages the pet state (energy, streak, total tasks done).
final class PetStateProvider
extends $AsyncNotifierProvider<PetState, Map<String, dynamic>> {
/// Manages the pet state (energy, streak, total tasks done).
PetStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'petStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$petStateHash();
@$internal
@override
PetState create() => PetState();
}
String _$petStateHash() => r'4ae2b5760d1c5f54099481b5b1729145dd0775bc';
/// Manages the pet state (energy, streak, total tasks done).
abstract class _$PetState extends $AsyncNotifier<Map<String, dynamic>> {
FutureOr<Map<String, dynamic>> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref
as $Ref<AsyncValue<Map<String, dynamic>>, Map<String, dynamic>>;
final element = ref.element as $ClassProviderElement<
AnyNotifier<AsyncValue<Map<String, dynamic>>, Map<String, dynamic>>,
AsyncValue<Map<String, dynamic>>,
Object?,
Object?>;
element.handleCreate(ref, build);
}
}
/// Derived provider for the pet's current mood.
@ProviderFor(petMood)
final petMoodProvider = PetMoodProvider._();
/// Derived provider for the pet's current mood.
final class PetMoodProvider
extends $FunctionalProvider<AsyncValue<PetMood>, PetMood, FutureOr<PetMood>>
with $FutureModifier<PetMood>, $FutureProvider<PetMood> {
/// Derived provider for the pet's current mood.
PetMoodProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'petMoodProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$petMoodHash();
@$internal
@override
$FutureProviderElement<PetMood> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<PetMood> create(Ref ref) {
return petMood(ref);
}
}
String _$petMoodHash() => r'f608d5d30377353de259575fc987bae85cbd5ecf';
@@ -0,0 +1,31 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'task_providers.g.dart';
// TODO: Replace with actual Drift AppDatabase once data layer is implemented.
/// Provides all tasks as a list.
@riverpod
class Tasks extends _$Tasks {
@override
Future<List<String>> build() async {
// TODO: Fetch from task repository.
return [];
}
}
/// Provides today's tasks filtered by date.
@riverpod
Future<List<String>> todayTasks(Ref ref) async {
final tasks = await ref.watch(tasksProvider.future);
// TODO: Filter by today's date once Task entity is defined.
return tasks;
}
/// Provides a single task by ID.
@riverpod
Future<String?> taskById(Ref ref, String id) async {
final tasks = await ref.watch(tasksProvider.future);
// TODO: Look up by actual ID once Task entity is defined.
return tasks.where((t) => t == id).firstOrNull;
}
@@ -0,0 +1,176 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'task_providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Provides all tasks as a list.
@ProviderFor(Tasks)
final tasksProvider = TasksProvider._();
/// Provides all tasks as a list.
final class TasksProvider extends $AsyncNotifierProvider<Tasks, List<String>> {
/// Provides all tasks as a list.
TasksProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'tasksProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tasksHash();
@$internal
@override
Tasks create() => Tasks();
}
String _$tasksHash() => r'0bc19ff9f5dc2f434086c53b504a68b003b8f4c1';
/// Provides all tasks as a list.
abstract class _$Tasks extends $AsyncNotifier<List<String>> {
FutureOr<List<String>> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<AsyncValue<List<String>>, List<String>>;
final element = ref.element as $ClassProviderElement<
AnyNotifier<AsyncValue<List<String>>, List<String>>,
AsyncValue<List<String>>,
Object?,
Object?>;
element.handleCreate(ref, build);
}
}
/// Provides today's tasks filtered by date.
@ProviderFor(todayTasks)
final todayTasksProvider = TodayTasksProvider._();
/// Provides today's tasks filtered by date.
final class TodayTasksProvider extends $FunctionalProvider<
AsyncValue<List<String>>, List<String>, FutureOr<List<String>>>
with $FutureModifier<List<String>>, $FutureProvider<List<String>> {
/// Provides today's tasks filtered by date.
TodayTasksProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'todayTasksProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$todayTasksHash();
@$internal
@override
$FutureProviderElement<List<String>> $createElement(
$ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<List<String>> create(Ref ref) {
return todayTasks(ref);
}
}
String _$todayTasksHash() => r'2f1951cfe4e0862205bc07dd583797db1db79027';
/// Provides a single task by ID.
@ProviderFor(taskById)
final taskByIdProvider = TaskByIdFamily._();
/// Provides a single task by ID.
final class TaskByIdProvider
extends $FunctionalProvider<AsyncValue<String?>, String?, FutureOr<String?>>
with $FutureModifier<String?>, $FutureProvider<String?> {
/// Provides a single task by ID.
TaskByIdProvider._(
{required TaskByIdFamily super.from, required String super.argument})
: super(
retry: null,
name: r'taskByIdProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$taskByIdHash();
@override
String toString() {
return r'taskByIdProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<String?> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<String?> create(Ref ref) {
final argument = this.argument as String;
return taskById(
ref,
argument,
);
}
@override
bool operator ==(Object other) {
return other is TaskByIdProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$taskByIdHash() => r'43c2bcb96afd2d7a22711c21d182b8e3a17a0b5c';
/// Provides a single task by ID.
final class TaskByIdFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<String?>, String> {
TaskByIdFamily._()
: super(
retry: null,
name: r'taskByIdProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// Provides a single task by ID.
TaskByIdProvider call(
String id,
) =>
TaskByIdProvider._(argument: id, from: this);
@override
String toString() => r'taskByIdProvider';
}
View File
@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
class PetScreen extends StatelessWidget {
const PetScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Mazlicek')),
body: const Center(child: Text('Pet')),
);
}
}
@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
class TasksScreen extends StatelessWidget {
const TasksScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Ukoly')),
body: const Center(child: Text('Tasks')),
);
}
}
@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
class ZenScreen extends StatelessWidget {
const ZenScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Zen')),
body: const Center(child: Text('Zen Mode')),
);
}
}
+15 -112
View File
@@ -1,122 +1,25 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'core/router/app_router.dart';
import 'core/theme/kittie_theme.dart';
void main() {
runApp(const MyApp());
runApp(const ProviderScope(child: KittieApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class KittieApp extends ConsumerWidget {
const KittieApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(appRouterProvider);
return MaterialApp.router(
title: 'KittieMobile',
theme: KittieTheme.light,
routerConfig: router,
debugShowCheckedModeBanner: false,
);
}
}
+92
View File
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../core/router/app_router.dart';
import '../../core/theme/kittie_colors.dart';
import '../../core/theme/kittie_typography.dart';
/// Main scaffold with bottom navigation bar (4 tabs).
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.child});
final Widget child;
static const _tabs = [
_TabItem(label: 'ukoly', icon: Icons.grid_view_rounded, path: Routes.tasks),
_TabItem(label: 'mazlicek', icon: Icons.pets_rounded, path: Routes.pet),
_TabItem(label: 'zen', icon: Icons.star_rounded, path: Routes.zen),
_TabItem(label: 'profil', icon: Icons.person_rounded, path: Routes.profile),
];
int _currentIndex(BuildContext context) {
final location = GoRouterState.of(context).uri.path;
for (var i = 0; i < _tabs.length; i++) {
if (location.startsWith(_tabs[i].path)) return i;
}
return 0;
}
@override
Widget build(BuildContext context) {
final currentIndex = _currentIndex(context);
return Scaffold(
body: child,
bottomNavigationBar: Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: KittieColors.creamBorder, width: 0.5),
),
),
child: BottomNavigationBar(
currentIndex: currentIndex,
onTap: (index) => context.go(_tabs[index].path),
items: List.generate(_tabs.length, (index) {
final tab = _tabs[index];
final isActive = index == currentIndex;
return BottomNavigationBarItem(
icon: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(tab.icon),
const SizedBox(height: 2),
if (isActive)
Container(
width: 4,
height: 4,
decoration: const BoxDecoration(
color: KittieColors.amber,
shape: BoxShape.circle,
),
)
else
const SizedBox(height: 4),
],
),
label: tab.label,
);
}),
selectedLabelStyle: KittieTypography.labelSmall.copyWith(
color: KittieColors.brown,
),
unselectedLabelStyle: KittieTypography.labelSmall.copyWith(
color: KittieColors.brownLight,
),
),
),
);
}
}
class _TabItem {
const _TabItem({
required this.label,
required this.icon,
required this.path,
});
final String label;
final IconData icon;
final String path;
}
+13
View File
@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profil')),
body: const Center(child: Text('Profile')),
);
}
}
+7 -22
View File
@@ -1,30 +1,15 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:kittie_mobile/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
testWidgets('App renders smoke test', (WidgetTester tester) async {
await tester.pumpWidget(
const ProviderScope(child: KittieApp()),
);
await tester.pumpAndSettle();
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('Tasks'), findsOneWidget);
});
}