In my code user can add animated widget dynamically by press button. Here is my parent class
class ParentWidget extends StatefulWidget {
const ParentWidget({Key? key}) : super(key: key);
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
List<Widget> animatedWidgetList=[];
@override
Widget build(BuildContext context) {
return Stack(
children: [
ElevatedButton(
onPressed:() {
animatedWidgetList.add(AnimatedWidget());// this is important
},
child: ButtonWidget()),
Stack(
children: animatedWidgetList,
),
],
);
}
}
Now, AnimatedWidget()
has simple icon and it is moving along path.
It also contain AnimationController
, Animation
and its Listener
.
Everything works perfectly as long as it clicks slowly. But whenever user tapping fast (10 tap/second) UI will confused and animation will not work perfect.
But after few time(1 to 2 seconds) everything will be ok.
ROOT CAUSE:
what happening here?
AnimtedWidget()
contains Listener.
_animation = Tween(begin: 0.0, end: 1.0).animate(_controller!)
..addListener(() {
setState(() {});
});
This setState(() {})
called many time in every second.
Suppose animation duration is 1 second and setState(() {})
called 10 times per second, than AnimatedWidget() rebuild 10 times per second.
And if animatedWidgetList
having 10 element of AnimatedWidget()
, than 100 time setState()
called in 1 second
So How do I figure out this ?