Flutter code creating laggy animation. What is wrong here? Flutter code creating laggy animation. What is wrong here? dart dart

Flutter code creating laggy animation. What is wrong here?


The whole purpose of using AnimationController is to listen to its events - that's what AnimatedBuilder does and rebuilds its subtree accordingly.

I will post here my overall recommendations on what to change in the code.


Remove setState - that's what makes your entire layout rebuild all over again, i.e. lags.

Also trigger _animeController listeners, i.e. AnimatedBuilder in your case - to rebuild itself.

accelerometerEvents.listen((AccelerometerEvent event) {  var a = ((event.x * 100).round() / 100).clamp(-1.0, 1.0) * -1;  var b = ((event.y * 100).round() / 100).clamp(-1.0, 1.0);  if ((x - a).abs() > 0.02 || (y - b).abs() > 0.02) {    x = a; y = b;    _animeController.value = _animeController.value; // Trigger controller's listeners  }});

Start animation in initState, instead of build. This is the second thing that produces lags in your case. .forward triggers rebuild of your widgets, which leads to an infinite loop.

@overridevoid initState() {  super.initState();  _animeController.forward();}

Use child property of your AnimatedBuilder to save up resources on rebuilding the avatar block every time. Also I'm not sure what Scaffold is here for - let's remove it if it's not needed.

AnimatedBuilder(  animation: _animeController,  builder: (context, child) => Transform(    transform: Matrix4.translationValues(_anime.value * width * x, _anime.value * height * y, 0.0),    child: child,  ),  child: Center(    child: CircleAvatar(      radius: 15.0,      backgroundColor: Colors.green,    ),  ),);

Follow Official Animations Tutorial to master Flutter animations.

Let me know if this helps.