我正在制作一个应用程序,其中每个页面都有相同的背景,并且背景上有不同的动画。我想在任何地方都使用背景,而不是多次创建背景,也不想在每次切换页面时破坏动画。有什么解决办法或建议吗?
您可以为背景及其动画创建一个单独的小部件。然后,您可以使用此背景小部件作为每个页面的背景。 例如:
class BackgroundPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
// Use Stack to layer the background behind other content
body: Stack(
children: [
// Background widget with animations
BackgroundWidget(),
// Page content
Center(
child: Text(
'Your Page Content Here',
style: TextStyle(fontSize: 20),
),
),
],
),
);
}
}
class BackgroundWidget extends StatefulWidget {
@override
_BackgroundWidgetState createState() => _BackgroundWidgetState();
}
class _BackgroundWidgetState extends State<BackgroundWidget>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 5),
)..repeat(reverse: true);
_animation = Tween<double>(begin: 0, end: 2 * 3.14).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.blue,
Colors.green,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
// Apply animations here
transform: Matrix4.translationValues(
0.0,
50 * sin(_animation.value), // Adjust this value based on your animation
0.0,
),
);
},
);
}
}