fix navbar matching when using global back button

This commit is contained in:
2025-08-06 00:53:37 +01:00
parent 115954f397
commit ae88847543
4 changed files with 92 additions and 9 deletions

View File

@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:mileograph_flutter/components/pages/calculator.dart';
import 'package:mileograph_flutter/components/pages/newEntry.dart';
import 'package:mileograph_flutter/components/pages/traction.dart';
import 'package:mileograph_flutter/components/pages/trips.dart';
import 'package:provider/provider.dart';
import 'package:mileograph_flutter/components/pages/legs.dart';
@@ -85,8 +87,14 @@ class MyApp extends StatelessWidget {
routes: [
GoRoute(path: '/', builder: (_, __) => const Dashboard()),
GoRoute(path: '/calculator', builder: (_, __) => CalculatorPage()),
GoRoute(
path: '/calculator/details',
builder: (_, __) => CalculatorPage(),
),
GoRoute(path: '/legs', builder: (_, __) => LegsPage()),
GoRoute(path: '/traction', builder: (_, __) => TractionPage()),
GoRoute(path: '/trips', builder: (_, __) => TripsPage()),
GoRoute(path: '/add', builder: (_, __) => NewEntryPage()),
],
),
GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
@@ -146,15 +154,29 @@ class MyHomePage extends StatefulWidget {
}
class _MyHomePageState extends State<MyHomePage> {
int pageIndex = 0;
final List<String> contentPages = [
"/",
"/calculator",
"/legs",
"/traction",
"/",
"/trips",
];
int _getIndexFromLocation(String location) {
int newIndex = contentPages.indexWhere((path) => location == path);
if (newIndex < 0) {
return 0;
}
return newIndex;
}
void _onItemTapped(int index, int currentIndex) {
if (index < 0 || index >= contentPages.length || index == currentIndex)
return;
context.push(contentPages[index]);
_getIndexFromLocation(contentPages[index]);
}
bool loggedIn = false;
bool _fetched = false;
@@ -184,7 +206,8 @@ class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
Widget currentPage;
final location = GoRouterState.of(context).uri.toString();
final pageIndex = _getIndexFromLocation(location);
final data = context.watch<DataService>();
final auth = context.read<AuthService>();
@@ -232,10 +255,7 @@ class _MyHomePageState extends State<MyHomePage> {
bottomNavigationBar: NavigationBar(
selectedIndex: pageIndex,
onDestinationSelected: (int index) {
setState(() {
pageIndex = index;
context.push(contentPages[index]);
});
_onItemTapped(index, pageIndex);
},
destinations: [
NavigationDestination(icon: Icon(Icons.home), label: "Home"),
@@ -247,7 +267,7 @@ class _MyHomePageState extends State<MyHomePage> {
),
body: currentPage,
floatingActionButton: FloatingActionButton(
onPressed: null,
onPressed: () => {context.push("/add")},
tooltip: 'New Entry',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.