finnow/flutter_app/lib/router.dart

96 lines
3.2 KiB
Dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'api/profile.dart';
import 'auth/model.dart';
import 'pages/login_page.dart';
import 'main.dart';
import 'pages/profile_page.dart';
import 'pages/profiles_page.dart';
import 'pages/register_page.dart';
import 'pages/user_account_page.dart';
GoRouter getRouterConfig() {
return GoRouter(routes: [
GoRoute(path: '/login', builder: (ctx, state) => const LoginPage()),
GoRoute(path: '/register', builder: (ctx, state) => const RegisterPage()),
// Once a user has logged in, they're directed to a scaffold for the /profiles page.
ShellRoute(
builder: getAppScaffold,
redirect: (context, state) {
// If the user isn't authenticated when they navigate here, send them
// back to /login.
final bool authenticated =
getIt<AuthenticationModel>().state.authenticated();
return authenticated ? null : '/login';
},
routes: [
// The "/" route is just a dummy landing route that redirects to
// /profiles if the user is authenticated, or /login otherwise.
GoRoute(
path: '/',
redirect: (context, state) {
final bool authenticated =
getIt<AuthenticationModel>().state.authenticated();
return authenticated ? '/profiles' : '/login';
}),
GoRoute(
path: '/profiles',
builder: (context, state) => const ProfilesPage(),
routes: [
GoRoute(
path: ':profile',
builder: (context, state) {
final String profileName =
state.pathParameters['profile']!;
return ProfilePage(Profile(profileName));
}),
]),
GoRoute(
path: '/user-account',
builder: (ctx, state) => UserAccountPage(getIt<AuthenticationModel>().state as Authenticated)
)
]),
]);
}
/// Gets the scaffold for the main authenticated view of the app, which is
/// where the user is viewing their set of profiles.
Widget getAppScaffold(BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: child,
appBar: AppBar(
title: const Text('Finnow'),
backgroundColor: Colors.grey,
actions: [
IconButton(
onPressed: () {
final router = getIt<GoRouter>();
router.push('/user-account');
},
icon: const Icon(Icons.account_circle)
),
IconButton(
onPressed: () =>
getIt<AuthenticationModel>().state = Unauthenticated(),
icon: const Icon(Icons.logout))
],
),
bottomNavigationBar:
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
BackButton(
onPressed: () {
GoRouter router = getIt<GoRouter>();
if (router.canPop()) router.pop();
},
),
IconButton(
onPressed: () {
GoRouter router = getIt<GoRouter>();
router.replace('/profiles');
},
icon: const Icon(Icons.home))
]),
);
}