Change the bottom navigation index without opening screen on button press
I have a persistent bottom navigation bar with five tabs. On the index 2 screen, there are three tabs, with the last one being "Cart". all my screens, there's a floating cart details widget visible across all tabs. When the user clicks on the floating cart details, I want to navigate to tab 3 of index 2, now I can push to tab 3 but index is not chaning.
onpresed is comming all screen since I have flaoting cart details in all screen when I click I want to always change index to 2 and then 2 tab sicne cart screen is tab
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (parentContext, animation, secondaryAnimation) {
return HomeMenues(2);
},
),
);
this olny push this creen for tab 3 but is not changing index
Answers
To achieve your desired behavior of navigating to tab 3 of index 2 while changing the index to 2 as well, you can use a combination of a bottom navigation bar and a tab controller. Here's a step-by-step approach to implement this in Flutter:
- Define your bottom navigation bar with five tabs.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My App"),
),
body: IndexedStack(
index: _currentIndex,
children: <Widget>[
Screen1(),
Screen2(),
Screen3(),
Screen4(),
Screen5(),
],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
label: 'Cart',
),
BottomNavigationBarItem(
icon: Icon(Icons.notifications),
label: 'Notifications',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
);
}
}
- In your floating cart details widget, when the user clicks on it, you can navigate to tab 3 of index 2 while setting the current index to 2 as well.
GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MyHomePage(
currentIndex: 2,
),
),
);
},
child: YourFloatingCartWidget(),
),
By using IndexedStack
for managing different screens and BottomNavigationBar
for navigation, along with proper navigation logic in your floating cart details widget, you can achieve the desired behavior of changing both the index and tab when navigating to tab 3 of index 2.