I have a separate Appbar file that I use for multiple pages. I want to be able to choose if I want to display the actions Iconbutton because I don’t want to have it on some pages. I want to keep all the code for the Iconbutton in my appbar file since it’s a lot of code. I have tried in other projects to put in the actions separately in the page file, but I don’t want to have to do that this time since I just want to be able to choose if the actions (IconButton) should be displayed or not basically.
This is my appbar code:
class MyAppBar extends StatefulWidget {
const MyAppBar({super.key});
@override
State<MyAppBar> createState() => _MyAppBarState();
}
class _MyAppBarState extends State<MyAppBar> with SingleTickerProviderStateMixin {
final player = AudioPlayer();
// create the animation controller
late AnimationController _animationController;
// initiate animation controller
@override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this, duration: const Duration(seconds: 1));
}
//method for when user taps icon
bool videoPlaying = false;
void _iconTapped() {
if (videoPlaying == false) {
playSound();
_animationController.forward();
videoPlaying = true;
} else {
pauseSound();
_animationController.reverse();
videoPlaying = false;
}
}
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.transparent,
toolbarHeight: 100,
centerTitle: true,
iconTheme: const IconThemeData(color: Colors.black),
flexibleSpace: const Image(
image: AssetImage('assets/images/backgroundappbar.png'),
fit: BoxFit.cover,
),
title: Center(
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, '/homepage'
);
},
icon: Image.asset('assets/images/ha_logo.png', height: 80, width: 80,)),
),
actions: [
IconButton(
onPressed: _iconTapped,
icon: AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: _animationController,
),
),
],
);
}
// Play audio
Future<void> playSound() async {
String audioPath = "audio/00_HarapAlb.mp3";
await player.play(AssetSource(audioPath));
}
//Pause audio
void pauseSound(){
player.pause();
}
}
3
Answers
You could just add a flag prop on your custom AppBar like so:
and then on your AppBar’s actions just set a conditional statement:
so that whenever you don’t want to show the actions you call:
MyAppBar(showAction: false)
instead of justMyAppBar()
You can handle this by using just a flag variable:
And in your AppBar: