Flutter - Error while creating a widget around Rive

244 Views Asked by At

To use rive in multiple places, I created a wrapper widget around the Rive widget.

//imports...
class RiveAnimation extends StatefulWidget {
  final String path;
  final String animation;
  final Alignment alignment;
  final bool useArtboardSize;
  RiveAnimation({
    @required this.path,
    this.animation = animTrigger,
    this.alignment = Alignment.center,
    this.useArtboardSize = true,
  });
  @override
  _RiveAnimationState createState() => _RiveAnimationState();
}

class _RiveAnimationState extends State<RiveAnimation> {
  Artboard _riveArtboard;
  RiveAnimationController _controller;

  @override
  void initState() {
    rootBundle.load(widget.path).then(
      (data) async {
        print('animation loaded');
        final RiveFile file = RiveFile.import(data);
        if (file != null) {
          final Artboard artboard = file.mainArtboard;
          artboard.addController(
            _controller = SimpleAnimation(widget.animation),
          );
          setState(() {
            _riveArtboard = artboard;
          });
        }
      },
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Rive(
      artboard: _riveArtboard,
      alignment: widget.alignment,
      useArtboardSize: widget.useArtboardSize,
      fit: BoxFit.fill,
    );
  }
}

While using this widget, I get an error saying:

I/flutter ( 7139): The getter 'redraw' was called on null.
I/flutter ( 7139): Receiver: null
I/flutter ( 7139): Tried calling: redraw

Sometimes, the Animation gets displayed but other times I see the Flutter error screen.

Thank you.

1

There are 1 best solutions below

0
On

Try to call

super.initState();

before loading the animation.

  @override
  void initState() {
    super.initState();
    rootBundle.load(widget.path).then(
      (data) async {
        print('animation loaded');
        final RiveFile file = RiveFile.import(data);
        if (file != null) {
          final Artboard artboard = file.mainArtboard;
          artboard.addController(
            _controller = SimpleAnimation(widget.animation),
          );
          setState(() {
            _riveArtboard = artboard;
          });
        }
      },
    );
  }