From 460f3471b587c9c51e9f0b14e54b440c2cce2e0f Mon Sep 17 00:00:00 2001 From: Kingkor Roy Tirtho Date: Tue, 26 Sep 2023 22:57:12 +0600 Subject: [PATCH] chore: fix route change error --- lib/pages/root/root_app.dart | 48 ++++++++++++++---------------------- 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/lib/pages/root/root_app.dart b/lib/pages/root/root_app.dart index 9e6610c5..3a0bd643 100644 --- a/lib/pages/root/root_app.dart +++ b/lib/pages/root/root_app.dart @@ -19,10 +19,10 @@ import 'package:spotube/provider/download_manager_provider.dart'; import 'package:spotube/utils/persisted_state_notifier.dart'; const rootPaths = { - 0: "/", - 1: "/search", - 2: "/library", - 3: "/lyrics", + "/": 0, + "/search": 1, + "/library": 2, + "/lyrics": 3, }; class RootApp extends HookConsumerWidget { @@ -34,7 +34,6 @@ class RootApp extends HookConsumerWidget { @override Widget build(BuildContext context, ref) { - final index = useState(0); final isMounted = useIsMounted(); final showingDialogCompleter = useRef(Completer()..complete()); final downloader = ref.watch(downloadManagerProvider); @@ -42,20 +41,6 @@ class RootApp extends HookConsumerWidget { final theme = Theme.of(context); final location = GoRouterState.of(context).matchedLocation; - useEffect(() { - final newIndex = rootPaths.entries.firstWhereOrNull((e) { - if (e.value == "/" || location == "/") { - return location == e.value; - } - return location.startsWith(e.value); - })?.key; - if (newIndex != null) { - index.value = newIndex; - } - - return null; - }, [location]); - useEffect(() { WidgetsBinding.instance.addPostFrameCallback((_) async { final sharedPreferences = await SharedPreferences.getInstance(); @@ -163,13 +148,21 @@ class RootApp extends HookConsumerWidget { return null; }, [backgroundColor]); + void onSelectIndexChanged(int d) { + final invertedRouteMap = + rootPaths.map((key, value) => MapEntry(value, key)); + + if (context.mounted) { + WidgetsBinding.instance.addPostFrameCallback((_) { + GoRouter.of(context).go(invertedRouteMap[d]!); + }); + } + } + return Scaffold( body: Sidebar( - selectedIndex: index.value, - onSelectedIndexChanged: (i) { - index.value = i; - GoRouter.of(context).go(rootPaths[index.value]!); - }, + selectedIndex: rootPaths[location] ?? 0, + onSelectedIndexChanged: onSelectIndexChanged, child: child, ), extendBody: true, @@ -178,11 +171,8 @@ class RootApp extends HookConsumerWidget { children: [ BottomPlayer(), SpotubeNavigationBar( - selectedIndex: index.value, - onSelectedIndexChanged: (selectedIndex) { - index.value = selectedIndex; - GoRouter.of(context).go(rootPaths[selectedIndex]!); - }, + selectedIndex: rootPaths[location] ?? 0, + onSelectedIndexChanged: onSelectIndexChanged, ), ], ),