我有一个单独的 Appbar 文件,用于多个页面。我希望能够选择是否要显示操作图标按钮,因为我不想在某些页面上显示它。我想将 Iconbutton 的所有代码保留在我的 appbar 文件中,因为它有很多代码。我曾尝试在其他项目中将操作单独放入页面文件中,但这次我不想这样做,因为我只想能够选择是否应显示操作(IconButton)基本上。
这是我的应用程序栏代码:
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();
}
}
您可以在自定义 AppBar 上添加一个标志道具,如下所示:
class MyAppBar extends StatefulWidget {
const MyAppBar({this.showAction = true, super.key});
final bool showAction;
@override
State<MyAppBar> createState() => _MyAppBarState();
}
然后在 AppBar 的操作上设置一个条件语句:
actions: [
if (widget.showAction)
IconButton(
onPressed: _iconTapped,
icon: AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: _animationController,
),
),
],
这样每当您不想显示您调用的操作时:
MyAppBar(showAction: false)
而不仅仅是MyAppBar()