Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the background continuously in flutter

Tags:

flutter

I know how to change the background but I need it to be changing continuously.

How do I achieve this?

like image 891
noun lace Avatar asked Jun 14 '20 08:06

noun lace


2 Answers

you could use an AnimatedContainer and reset the target color when the animation is over. For a smooth Transition, I suggest a List of Colors you can loop over, you can do the same with the Alignment.

Example:

enter image description here

Source Code for the Example:

import 'package:flutter/material.dart';

class AnimatedGradient extends StatefulWidget {
  @override
  _AnimatedGradientState createState() => _AnimatedGradientState();
}

class _AnimatedGradientState extends State<AnimatedGradient> {
  List<Color> colorList = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.yellow
  ];
  List<Alignment> alignmentList = [
    Alignment.bottomLeft,
    Alignment.bottomRight,
    Alignment.topRight,
    Alignment.topLeft,
  ];
  int index = 0;
  Color bottomColor = Colors.red;
  Color topColor = Colors.yellow;
  Alignment begin = Alignment.bottomLeft;
  Alignment end = Alignment.topRight;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: [
        AnimatedContainer(
          duration: Duration(seconds: 2),
          onEnd: () {
            setState(() {
              index = index + 1;
              // animate the color
              bottomColor = colorList[index % colorList.length];
              topColor = colorList[(index + 1) % colorList.length];

              //// animate the alignment
              // begin = alignmentList[index % alignmentList.length];
              // end = alignmentList[(index + 2) % alignmentList.length];
            });
          },
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: begin, end: end, colors: [bottomColor, topColor])),
        ),
        Positioned.fill(
          child: IconButton(
            icon: Icon(Icons.play_arrow),
            onPressed: () {
              setState(() {
                bottomColor = Colors.blue;
              });
            },
          ),
        )
      ],
    ));
  }
}

like image 182
SeriForte Avatar answered Oct 10 '22 23:10

SeriForte


To auto animate the gradient just add this block of code in @override Widget build(BuildContext context) {} method of SeriForte's code.

Future.delayed(const Duration(milliseconds: 10), () {
  setState(() {
    bottomColor = Colors.blue;
  });
});
like image 30
Rahul Saliya Avatar answered Oct 10 '22 22:10

Rahul Saliya