I have some animation code that changes background color infinitely
but the problem is I want to do this without a button trigger
and I want this to be automated at first time (when it's firstly loading)
below is code
I`m so stuck could anyone help please
the purpose is to animate without a trigger, it automatically runs animation that changes background
import 'package:flutter/material.dart';
class ScreenTime extends StatefulWidget {
@override
_ScreenTimeState createState() => _ScreenTimeState();
}
class _ScreenTimeState extends State<ScreenTime> {
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.black54;
Color topColor = Colors.white10;
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 keep as much as your original implementation as possible while fixing the problem, doing
WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {bottomColor = Colors.blue;}));
in initState
would not pose an issue. This is as long as it's done in initState
. Calling it in build
would lead to an undesirable extra infinite loop.
However, using an AnimationController
on repeat
would almost certainly be a cleaner implmentation.
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