xvrh / lottie-flutter

Render After Effects animations natively on Flutter. This package is a pure Dart implementation of a Lottie player.
https://pub.dev/packages/lottie
MIT License
1.16k stars 196 forks source link

Example File: animation_full_control.dart has error #222

Open rdcoder33 opened 2 years ago

rdcoder33 commented 2 years ago

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.

xvrh commented 2 years ago

@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?