I just want to know, can I make bottomnavigationbar reusable, because what i saw in the other similar problem is just they use list of screen and then using scaffold that it makes cannot be reusable for my cases, and I just want to know is this even possible?
import 'package:conditional/HistoryScreen.dart';
import 'package:conditional/HomeScreen.dart';
import 'package:flutter/material.dart';
class NavBar extends StatefulWidget{
NavBar({Key? key}):super(key: key);
@override
_NavBar createState() => _NavBar();
}
class _NavBar extends State<NavBar>{
int currentIndex = 0;
@override
Widget build(BuildContext context){
return BottomNavigationBar(
currentIndex: currentIndex,
onTap: (index){
setState(() {
currentIndex = index;
});
switch(index){
case 0:
Navigator.push(context, MaterialPageRoute(builder: (context) => HomeScreen()));
break;
case 1:
Navigator.push(context, MaterialPageRoute(builder: (context) => HistoryScreen()), );
break;
}
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
activeIcon: Icon(Icons.home, color: currentIndex == 0 ? Colors.red : Colors.grey),
label: "Home"),
BottomNavigationBarItem(
icon:Icon(Icons.history),
activeIcon: Icon(Icons.history, color: currentIndex == 1 ? Colors.red : Colors.grey),
label: "History" )
],
selectedItemColor: Colors.red,
);
}
}
import 'package:conditional/NavBar.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget{
HomeScreen({Key? key}):super(key: key);
@override
Widget build(BuildContext context){
return Scaffold(
body: Center(child: Text("This is Homescreen"),),
bottomNavigationBar: NavBar(),
);
}
}
import 'package:conditional/NavBar.dart';
import 'package:flutter/material.dart';
class HistoryScreen extends StatefulWidget{
HistoryScreen({Key? key}):super(key: key);
@override
_HistoryScreen createState()=> _HistoryScreen();
}
class _HistoryScreen extends State<HistoryScreen>{
@override
Widget build(BuildContext context){
return Scaffold(
body: Text("This is History Screen"),
bottomNavigationBar: NavBar(),
);
}
}
the main problem is was, if I clicked the history button, the home button still red and I don’t event know where’s the problem, But the navigator is working correctly as intended just the Color when its clicked, can you guys help me?
2
Answers
You can create a reusable BottomNavigationBar in Flutter by encapsulating it within a separate widget.
Then, you can use this ReusableBottomNavigationBar widget in any screen where you want to display a bottom navigation bar. Here’s an example:
to acheive what you want, you can use the IndexedStacked widget. your code will look like this: