Same animated background widget on every page in flutter

46 views Asked by At

I was making an app where every page has the same background and the background has different animations happening all over it. I want to use the background everywhere without creating it multiple times and disrupting the animations every time I transition through pages. Any solutions or suggestions?

1

There are 1 answers

0
Hassan On

You can create a separate widget for the background with its animations. Then, you can use this background widget as the background for each page. For example:

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,
          ),
        );
      },
    );
  }
}