-
Notifications
You must be signed in to change notification settings - Fork 11
How to animate with rive
To build the animation you can use the rive animation builder website.
A service has been created to simplify the starting and the initialization of the animation. You can use the service in a viewmodel like that:
class MyCustomViewModel extends BaseViewModel {
/// Used to access the rive animations service
final RiveAnimationService _riveAnimationService = locator<RiveAnimationService>();
Artboard _artboard;
Artboard get artboard => _artboard;
/// REST OF FILE ...
Future<void> loadRiveAnimation() async {
try {
_artboard = await _riveAnimationService.loadRiveFile(
riveFileName: 'dot_jumping');
} catch (e) {
_analyticsService.logError(tag,
"An Error has occured during rive animation $_riveAnimationFileName loading.");
}
}
void startRiveAnimation() {
try {
_riveAnimationService.addControllerToAnimation(artboard: _artboard);
} catch (e) {
_analyticsService.logError(
tag, "An Error has occured during rive animation start.");
}
}
}
The function load rive animation takes one positional argument: _riveAnimationService.loadRiveFile(riveFileName: 'sample_animation');
. This function load the rive file of the name passed in parameter. Make sure to add the rive file (*.riv
) into the folder assets/animations/
. If any error happens during the loading an AnimationException
will be thrown. An artboard will be return if the loading has been successful.
The function that start rive animation takes one required positional argument and one optional positional argument : _riveAnimationService.startRiveFile(artboard: _artboard, controller: SimpleAnimation('animation_1'));
. An artboard object is required by the function which is loaded using the loadRiveFile function. If the animation you are trying to start needs a controller other than a SimpleAnimation, you can optionally pass it as the second parameter.
It's important to use the startRiveAnimation function that you created inside a setState()
(StatefulWidget) like this: setState(() => viewModel.startRiveAnimation())
.
To start an animation as soon as the page is loaded, you can use this structure:
@override
void initState() {
viewModel = NotFoundViewModel(pageName: widget.pageName);
viewModel
.loadRiveAnimation()
.then((_) => setState(() => viewModel.startRiveAnimation()));
}
Otherwise you can launch an animation based on a click by calling the loadRiveAnimation()
from the initState and the setState(() => viewModel.startRiveAnimation())
from a button on click event.
See this for a complete tour of what rive library can do.
Home | Installation | How To