I know how to change the background but I need it to be changing continuously.
How do I achieve this?
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:
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;
});
},
),
)
],
));
}
}
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With