I want to use a BottomAppBar and due to technical reasons I cannot use the BottomNavigationBar.
How do I define the color of my icons depending on which screen I’m on? I.e. when I am on Screen A, the Sceen A Icon in the BottomAppBar should be white, but if I am on Screen B, it should be grey and the Screen B icon should be white.
My first idea was to use a ternary expression:
class Bar extends StatefulWidget {
const Bar({super.key});
@override
State<Bar> createState() => _BarState();
}
class _BarState extends State<Bar> {
@override
Widget build(BuildContext context) {
var route = ModalRoute.of(context);
return SafeArea(
child: BottomAppBar(
color: Colors.white,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => ScreenA())),
icon: Icon(
Icons.abc,
color: route==ScreenA()?Colors.white:Colors.grey,
),
),
IconButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const ScreenB())),
icon: Icon(
Icons.abc,
color: route==ScreenB()?Colors.white:Colors.grey,
),
),
],
),
),
);
}
}
I think I did not correctly define the variable for which screen I’m on currently.
2
Answers
Output of this code:
ScreenA:
ScreenB:
You can use in your project. I hope I have helped. Enjoy your work.
Try this example and if you need individual colors for every menu, you can try to use multi-condition ternary operator. I’ve added an example for you.