I've been working on a Flutter app for a few days now.
I've implemented a NavigationRail for my app. It works pretty well, excepted for one thing.
When I tap on a NavigationRailDestination, it calls the function updateRoute(index) and goes to the required route.
My problem is that, the selectedIndex property udpates, but then, when the new route is loaded, the selectedIndex goes back to 0.
Here is my code :
class SidebarDrawer extends StatefulWidget {
final VoidCallback callbackOnScreenChange;
SidebarDrawer({@required this.callbackOnScreenChange});
@override
_SidebarDrawerState createState() => _SidebarDrawerState();
}
class _SidebarDrawerState extends State<SidebarDrawer> {
int index = 0;
@override
Widget build(BuildContext context) => NavigationRail(
extended: isExtended,
onDestinationSelected: (index) => updateRoute(index),
selectedIndex: index,
leading: IconButton(
icon: Icon(Icons.reorder),
onPressed: () => setState(() => isExtended = !isExtended),
),
destinations: <NavigationRailDestination>[
<Some NavigationRailDestination>
],
);
void updateRoute(index) {
setState(() => this.index = index);
switch (index) {
case 0:
return navigateToScreen(
context, '/home', widget.callbackOnScreenChange);
case 1:
return navigateToScreen(
context, '/orderManager', widget.callbackOnScreenChange);
case 2:
return navigateToScreen(
context, '/manualControl', widget.callbackOnScreenChange);
default:
return navigateToScreen(
context, '/home', widget.callbackOnScreenChange);
}
}
The function navigateToScreen() :
/// Navigate to given widget
void navigateToScreen(BuildContext context, String route,
VoidCallback callbackOnScreenChange) async {
// Call callback on screen change
if (callbackOnScreenChange != null) {
callbackOnScreenChange();
}
// Check the current route
String currentRoute = ModalRoute.of(context).settings.name;
// If the current route is not the same as the new route change the screen
if (currentRoute != route) {
await Navigator.pushNamed(context, route);
}
}
I am new to Flutter, I am struggling a bit to understand how does the state works and updates.
I would really appreciate if you could help me understand it please !