I want to change the background color of container with animation infinitely. I know that i can do that using AnimatedContainer like below code:
AnimatedContainer(
duration: Duration(seconds: 2),
color: _color,
curve: Curves.fastOutSlowIn,
height: 200,
width: 200,
),
FlatButton(
child: Text('Change Color'),
onPressed: (){
setState((){
_color= Colors.red;
});
},
),
but i dont want to change the color and setState using press a button. I want to change it when the app start runnig, without press anything. How can i achieve this?
I think i must setState after changing value of color but i dont know how to setState without click on something.
also i did this:
AnimatedContainer(
color: animatedBackgroundColor,
duration: Duration(seconds: 2),
onEnd: () => setState(() {
animatedBackgroundColor = const Color.fromARGB(255, 197, 14, 14);
}),
)
but it didnt change anything. I think that after the widget is created and its color is set, a button should be clicked at least once to change the animatedBackgroundColor
and then the animation starts. but i want it without button click and start change from current color to the color i set in onEnd
.
You can do something like this
@override
void initState() {
super.initState();
// Start a timer to change the color after 2 seconds
Timer(Duration(seconds: 2), () {
setState(() {
_color = Colors.red; // Change color to red after 2 seconds
});
});
}
And in you animated container
AnimatedContainer(
duration: Duration(seconds: 2),
color: _color,
curve: Curves.fastOutSlowIn,
height: 200,
width: 200,
onEnd: () => setState(() {
animatedBackgroundColor = Colors.green;
}),
),