lottie-flutter icon indicating copy to clipboard operation
lottie-flutter copied to clipboard

Example File: animation_full_control.dart has error

Open rdcoder33 opened this issue 3 years ago • 1 comments

So the example file of this repository, in example >> lib >> animation_full_control.dart there is a following error:

════════ Exception caught by animation library ═════════════════════════════════
The following assertion was thrown while notifying listeners for AnimationController:
setState() or markNeedsBuild() called during build.

This LottieWidget widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: LottieWidget
    state: _LottieWidgetState#d588f(tickers: tracking 1 ticker)

This is because, SetState is used in initState,

@override
  void initState() {
    _controller = AnimationController(vsync: this)
      ..addListener(() {
        setState(() {
          // Rebuild the widget at each frame to update the "progress" label.
        });
      });
    super.initState();
  }

But removing SetState, the code doesn't work expectedly and we get no control over frame.

Adding WidgetsBinding.instance.addPostFrameCallback solves the issue:

@override
  void initState() {
    _controller = AnimationController(vsync: this);
    WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {
          _controller
            .addListener(() {
              setState(() {
                // Rebuild the widget at each frame to update the "progress" label.
              });
            });
        }));

    super.initState();
  }

This method works, but let me know if you guys have a better solution.

rdcoder33 avatar Jun 25 '22 14:06 rdcoder33

@rdcoder33 I'm not able to reproduce the error your see. Did you change anything else in the file compared to the version in the repo?

xvrh avatar Jul 27 '22 12:07 xvrh