Flutter set initial input value for Rive animation

179 Views Asked by At

I have a rive animation in my Flutter app and I would like to set the initial value for an input, so I can control at which point the animation starts. But I can't get it done.

This is what I've got:

  context.rive.dataBalloonsRIV.copyWith(
    fit: BoxFit.fill,
    onInit: (artboard) async {
      _controller = StateMachineController.fromArtboard(
        artboard,
        _stateMachine,
      );

      if (_controller != null) {
        artboard.addController(_controller!);
        _amountInput = _controller!.findInput<double>('state');
        final startInput = _controller!.findInput<bool>('start');

        _amountInput?.value = 3;
        startInput?.value = true;
      }
      setState(
        () => (),
      );
    },
  ),

With this the animation will animate from start to inputValue 3.

I found this on the official rive docs, where an initialValue can be set. This sounds exactly like what I need, but I can't find a way to implement this in Flutter.

Is this possible? Has anyone done this before? Let me know if you need any more information.

1

There are 1 best solutions below

9
Frederik Behrens On

Yes, it is.

I have also struggled with this some time ago.

In my case, I have this method in my class to get the Rive Animation as a Widget:

Widget getWidget(double width) {
  return SizedBox(
    width: width,
    height: width,
    child: RiveAnimation.asset(
      "assets/rive/courses/$_fileName",
      controllers: [_controller],
      animations: [_animationName],
      artboard: _artboardName,
      fit: BoxFit.contain,
      stateMachines: [_stateMachineName],
      onInit: _onRiveInit,
    ),
  );
}

The "onInit:" points to my void function:

void _onRiveInit(Artboard artboard) {
  _stateMachineController = StateMachineController.fromArtboard(artboard, _stateMachineName)!;
  _addSMINumberToController(riveNumber);
  artboard.addController(_stateMachineController);
}

The "_addSMINumberToController" does, what I assume you need.

void _addSMINumberToController(RiveNumber num) {
  num.number = _stateMachineController.findInput<double>(num.location) as SMINumber;
  num.number!.change(num.value);
}

Note that the "RiveNumber" class is custom, and you can figure your own way out of it. My class looks like this:

class RiveNumber {
  SMINumber? number;
  String location;
  double value;
  RiveNumber({this.number, required this.location, required this.value});
}