### Complete Controller Setup with Selectors Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Example of setting up a RiveWidgetController with specific artboard and state machine selectors by name. ```dart final riveFile = await File.asset( 'assets/game.riv', riveFactory: Factory.rive, ); final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byName('GameBoard'), stateMachineSelector: StateMachineSelector.byName('PlayerController'), ); return RiveWidget(controller: controller); ``` -------------------------------- ### Run rive_native Setup Script Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Execute the rive_native setup script to download platform-specific libraries. Use the --verbose flag for detailed output and --clean to reset the setup. ```bash dart run rive_native:setup --verbose --clean --platform macos ``` -------------------------------- ### Unpack and Run Rive Flutter Example App Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Steps to unpack the Rive package, navigate to the example directory, set up platform folders, fetch dependencies, and run the example app. ```bash dart pub unpack rive # Unpack the package source code and example app cd rive/example # Navigate to the example folder flutter create . # Create the platform folders flutter pub get # Fetch dependencies flutter run # Run the example app ``` -------------------------------- ### Clone and Run Rive Flutter Example Source: https://github.com/rive-app/rive-flutter/blob/master/example/README.md Clone the Rive Flutter repository and run the example app. This method requires building native libraries locally. ```bash git clone https://github.com/rive-app/rive-flutter cd rive-flutter/example flutter pub get flutter run ``` -------------------------------- ### Patterns and Examples Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/MANIFEST.txt Collection of 10 real-world usage patterns with complete code examples for the Rive Flutter package. ```APIDOC ## Usage Patterns and Examples ### Description Illustrates 10 practical, real-world usage scenarios for the Rive Flutter package, complete with production-ready code examples. ``` -------------------------------- ### Complete Game Screen Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md A full Flutter example of a game screen integrating Rive animations. It includes initialization, state management, error handling for Rive operations, and basic user interaction via a button. ```dart class GameScreen extends StatefulWidget { @override State createState() => _GameScreenState(); } class _GameScreenState extends State { late final FileLoader _loader; late RiveWidgetController _controller; ViewModelInstance? _vmi; @override void initState() { super.initState(); _init(); } Future _init() async { _loader = FileLoader.fromAsset( 'assets/game.riv', riveFactory: Factory.rive, ); try { final file = await _loader.file(); _controller = RiveWidgetController(file); _vmi = _controller.dataBind(DataBind.auto()); setState(() {}); } on RiveException catch (e) { print('Error: ${e.message}'); } } @override void dispose() { _loader.dispose(); _controller.dispose(); _vmi?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return _vmi == null ? const Center(child: CircularProgressIndicator()) : Column( children: [ Expanded( child: RiveWidget(controller: _controller), ), Padding( padding: const EdgeInsets.all(16), child: Row( children: [ ElevatedButton( onPressed: () => _vmi?.trigger('Jump')?.fire(), child: const Text('Jump'), ), ], ), ), ], ); } } ``` -------------------------------- ### Complete Rive Integration Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-controller.md This example demonstrates a complete integration of a Rive animation into a Flutter application. It includes loading the Rive file, initializing the controller, binding data, and displaying the Rive animation within a RiveWidget. ```dart class MyRiveScreen extends StatefulWidget { @override State createState() => _MyRiveScreenState(); } class _MyRiveScreenState extends State { late RiveWidgetController _controller; File? _riveFile; @override void initState() { super.initState(); _loadAndInitialize(); } Future _loadAndInitialize() async { _riveFile = await File.asset( 'assets/interactive_animation.riv', riveFactory: Factory.rive, ); _controller = RiveWidgetController( _riveFile!, artboardSelector: ArtboardSelector.byName('MainBoard'), ); // Bind data and access properties final vmi = _controller.dataBind(DataBind.auto()); if (vmi.number('score') case var scoreProperty?) { scoreProperty.value = 1000; } setState(() {}); } @override void dispose() { _controller.dispose(); _riveFile?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return _riveFile == null ? const Center(child: CircularProgressIndicator()) : RiveWidget(controller: _controller); } } ``` -------------------------------- ### Clean and Get Dependencies Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Standard Flutter commands to clean the project and fetch dependencies. Run these if you encounter build issues. ```bash flutter clean flutter pub get flutter run ``` -------------------------------- ### Manual Shared Texture Setup Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Manually create and manage a `SharedRenderTexture` for performance optimization. This involves using `RiveSurface` and passing the texture to `RiveWidget`. ```dart final sharedTexture = SharedRenderTexture.create( backgroundColor: Colors.white, ); Stack( children: [ RiveSurface(sharedTexture: sharedTexture), RiveWidget( controller: controller, sharedTexture: sharedTexture, ), ], ) ``` -------------------------------- ### Create Default ViewModel Instance Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-extensions.md Example demonstrating how to create and use a default ViewModel instance from a Rive file and artboard. This is useful for interacting with animations that have defined view models. ```dart final file = await File.asset( 'assets/animation.riv', riveFactory: Factory.rive, ); final artboard = file.defaultArtboard(); if (artboard != null) { final vmi = file.createDefaultViewModelInstance(artboard); if (vmi != null) { // Use the view model instance vmi.number('Health')?.value = 100; } } ``` -------------------------------- ### SharedRenderTexture Usage Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/shared-texture.md Example of creating a shared render texture with custom background color and device pixel ratio. ```dart final sharedTexture = SharedRenderTexture.create( backgroundColor: Colors.white, devicePixelRatio: MediaQuery.of(context).devicePixelRatio, ); ``` -------------------------------- ### Use Auto Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Example of using the auto-binding strategy to get a view model instance and modify its properties. ```dart final vmi = controller.dataBind(DataBind.auto()); // Use the bound instance if (vmi.number('health') case var health?) { health.value = 100; } ``` -------------------------------- ### Load Rive Files from Different Sources Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Provides examples for loading Rive files from assets, URLs, or existing file instances. Ensure the `riveFactory` is correctly set. ```dart FileLoader.fromAsset('assets/name.riv', riveFactory: Factory.rive) ``` ```dart FileLoader.fromUrl('https://...', riveFactory: Factory.rive) ``` ```dart FileLoader.fromFile(file, riveFactory: Factory.rive) ``` -------------------------------- ### Use Data Binding by Instance Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Example of binding a pre-created view model instance to the controller. The instance must be created elsewhere. ```dart // Create instance elsewhere final vmi = file.createDefaultViewModelInstance(artboard); // Use the instance later final boundVmi = controller.dataBind(DataBind.byInstance(vmi)); ``` -------------------------------- ### Component Lifecycle Management Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/README.md Provides examples of disposing Rive components to release resources, including FileLoader, controller, and vmi. ```dart loader.dispose() // Releases cached file controller.dispose() // Releases artboard and state machine vmi.dispose() // Releases data binding ``` -------------------------------- ### Use Empty Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Example of binding an empty view model instance. ```dart final vmi = controller.dataBind(DataBind.empty()); ``` -------------------------------- ### Factory Methods for Valid Implementations Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/README.md Shows examples of factory methods used with sealed classes to ensure only valid implementations are returned, such as ArtboardSelector.byName and DataBind.auto. ```dart ArtboardSelector.byName('name') // Returns ArtboardNamed DataBind.auto() // Returns AutoBind ``` -------------------------------- ### Build rive_native Libraries Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Build the native libraries for rive_native yourself instead of downloading prebuilt ones. Ensure you run 'flutter clean' first. Use the --build flag with the setup script. ```bash flutter clean # Important dart run rive_native:setup --verbose --clean --build --platform macos ``` -------------------------------- ### RiveLoading State Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-builder.md Use this snippet to display a loading indicator when the Rive file is being fetched and processed. It's part of the builder's switch statement for handling different Rive states. ```dart RiveWidgetBuilder( fileLoader: loader, builder: (context, state) => switch (state) { RiveLoading() => const Center( child: CircularProgressIndicator(), ), // ... }, ) ``` -------------------------------- ### Basic Data Binding with RiveWidgetController Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md This example shows how to initialize a RiveWidgetController, load an asset, and auto-bind the default exported view model. It demonstrates updating a number property ('Health') and includes dispose logic. ```dart class GameScreen extends StatefulWidget { @override State createState() => _GameScreenState(); } class _GameScreenState extends State { late RiveWidgetController _controller; late ViewModelInstance _vmi; File? _file; @override void initState() { super.initState(); _init(); } Future _init() async { _file = await File.asset( 'assets/game.riv', riveFactory: Factory.rive, ); _controller = RiveWidgetController(_file!); // Auto-bind the default exported view model _vmi = _controller.dataBind(DataBind.auto()); setState(() {}); } @override void dispose() { _vmi.dispose(); _controller.dispose(); _file?.dispose(); super.dispose(); } void _takeDamage(int amount) { if (_vmi.number('Health') case var health?) { health.value = (health.value - amount).clamp(0, 100); } } void _heal(int amount) { if (_vmi.number('Health') case var health?) { health.value = (health.value + amount).clamp(0, 100); } } @override Widget build(BuildContext context) { return _file == null ? const CircularProgressIndicator() : Column( children: [ Expanded( child: RiveWidget(controller: _controller), ), Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => _takeDamage(10), child: const Text('Take Damage'), ), ElevatedButton( onPressed: () => _heal(10), child: const Text('Heal'), ), ], ), ), ], ); } } ``` -------------------------------- ### RiveWidget with Responsive Layout Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget.md Implement responsive Rive animations by setting `fit` to `Fit.layout` and providing a `layoutScaleFactor`. This example scales the animation based on the screen width. ```dart @override Widget build(BuildContext context) { return RiveWidget( controller: _controller, fit: Fit.layout, layoutScaleFactor: MediaQuery.of(context).size.width / 800, ); } ``` -------------------------------- ### Using RivePanel for Shared Texture Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/shared-texture.md Demonstrates using RivePanel to automatically manage a shared texture for child RiveWidgets. Recommended for simpler setups. ```dart class MultiRiveListView extends StatelessWidget { @override Widget build(BuildContext context) { return RivePanel( backgroundColor: Colors.white, child: ListView.builder( itemCount: 10, itemBuilder: (context, index) { return RiveWidgetBuilder( fileLoader: FileLoader.fromAsset( 'assets/animation.riv', riveFactory: Factory.rive, ), builder: (context, state) => switch (state) { RiveLoading() => const SizedBox( height: 200, child: Center(child: CircularProgressIndicator()), ), RiveLoaded(:final controller) => SizedBox( height: 200, child: RiveWidget( controller: controller, useSharedTexture: true, // Use the panel's texture ), ), RiveFailed(:final error) => Text('Error: $error'), }, ); }, ), ); } } ``` -------------------------------- ### Error Recovery with Retry Logic Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/patterns.md This example shows how to use the `onFailed` callback to display a retry option when a Rive animation fails to load. It manages a retry count and limits retries to prevent infinite loops. ```dart class ErrorRecoveryExample extends StatefulWidget { @override State createState() => _ErrorRecoveryExampleState(); } class _ErrorRecoveryExampleState extends State { int _retryCount = 0; final int _maxRetries = 3; @override Widget build(BuildContext context) { return RiveWidgetBuilder( fileLoader: FileLoader.fromUrl( 'https://example.com/animation.riv', riveFactory: Factory.rive, ), onFailed: (error, stackTrace) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Failed to load: $error'), action: SnackBarAction( label: 'Retry', onPressed: () { if (_retryCount < _maxRetries) { setState(() => _retryCount++); } else { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Max retries reached'), ), ); } }, ), ), ); }, builder: (context, state) => switch (state) { RiveLoading() => const Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox(height: 16), Text('Loading animation...'), ], ), ), RiveLoaded(:final controller) => RiveWidget(controller: controller), RiveFailed(:final error) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.error_outline, size: 64, color: Colors.red), const SizedBox(height: 16), const Text('Failed to load animation'), const SizedBox(height: 8), Text( 'Error: $error', textAlign: TextAlign.center, ), if (_retryCount < _maxRetries) Padding( padding: const EdgeInsets.only(top: 16), child: ElevatedButton( onPressed: () => setState(() => _retryCount++), child: Text('Retry ($_retryCount/$_maxRetries)')), ), ], ), ), }, ); } } ``` -------------------------------- ### Choose Rive Renderer in Flutter Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Example of how to specify which renderer to use when loading a Rive file in Flutter. Options include the Rive renderer (`Factory.rive`) or the Flutter renderer (`Factory.flutter`). ```dart final riveFile = (await File.asset( 'assets/rewards.riv', // Choose which renderer to use riveFactory: Factory.rive, ))!; ``` -------------------------------- ### RiveFailed State Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-builder.md Implement this snippet to show an error message when the Rive file loading or initialization fails. It uses the `RiveFailed` state to access the error details for display. ```dart RiveWidgetBuilder( fileLoader: loader, builder: (context, state) => switch (state) { RiveFailed(:final error) => ErrorWidget.withDetails( message: error.toString(), error: FlutterError(error.toString()), ), // ... }, ) ``` -------------------------------- ### RiveLoaded State Example with Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-builder.md This snippet demonstrates how to render the Rive animation and display bound view model information when the Rive file is successfully loaded. It utilizes the `RiveLoaded` state, which provides the controller and an optional `viewModelInstance`. ```dart RiveWidgetBuilder( fileLoader: loader, dataBind: DataBind.auto(), builder: (context, state) => switch (state) { RiveLoaded(:final controller, :final viewModelInstance) => Column( children: [ RiveWidget(controller: controller), if (viewModelInstance != null) Text('Bound: ${viewModelInstance.viewModel?.name}'), ], ), // ... }, ) ``` -------------------------------- ### ViewModel Instantiation Methods Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Methods for creating instances of ViewModels. ```APIDOC ## ViewModel Instantiation ### `ViewModel.createDefaultInstance()` #### Description Creates a default instance of a ViewModel. Returns: `ViewModelInstance?` ### `ViewModel.createInstance()` #### Description Creates a generic instance of a ViewModel. Returns: `ViewModelInstance?` ### `ViewModel.createInstanceByName(String)` #### Description Creates a ViewModel instance by its name. Parameters: - **name** (String) - The name of the ViewModel to create. Returns: `ViewModelInstance?` ### `ViewModel.createInstanceByIndex(int)` #### Description Creates a ViewModel instance by its index. Parameters: - **index** (int) - The index of the ViewModel to create. Returns: `ViewModelInstance?` ### `File.createDefaultViewModelInstance(Artboard)` #### Description Creates a default ViewModel instance associated with a given Artboard. Parameters: - **Artboard** - The Artboard to associate the ViewModel instance with. Returns: `ViewModelInstance?` ``` -------------------------------- ### Selecting Artboard and State Machine by Index Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Demonstrates how to load a Rive file and select the first artboard and second state machine using their indices. ```dart // Load the first artboard and second state machine final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byIndex(0), stateMachineSelector: StateMachineSelector.byIndex(1), ); ``` -------------------------------- ### RiveWidgetBuilder with Auto Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-extensions.md Example of using RiveWidgetBuilder with DataBind.auto(), which internally utilizes createDefaultViewModelInstance for setting up the ViewModelInstance. ```dart RiveWidgetBuilder( fileLoader: loader, dataBind: DataBind.auto(), // Uses createDefaultViewModelInstance internally builder: (context, state) => switch (state) { RiveLoaded(:final viewModelInstance) => // ... // ... }, ) ``` -------------------------------- ### Get Shared Texture using of() Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/shared-texture.md Retrieves the nearest SharedRenderTexture from the widget tree. Creates a dependency on the inherited widget. ```dart static SharedRenderTexture? of(BuildContext context) ``` -------------------------------- ### Catch Controller Creation Errors Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Handle errors that may occur when creating a `RiveWidgetController`. This example catches both `RiveArtboardException` and `RiveStateMachineException`. ```dart try { final controller = RiveWidgetController( file, artboardSelector: ArtboardSelector.byName('Nonexistent'), ); } on RiveArtboardException catch (e) { print('Artboard error: ${e.message}'); } on RiveStateMachineException catch (e) { print('State machine error: ${e.message}'); } ``` -------------------------------- ### Combine FileLoader with ViewModel Creation Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-extensions.md Demonstrates loading a Rive file using FileLoader and then creating a default ViewModel instance from the loaded file and its artboard. ```dart final loader = FileLoader.fromAsset( 'assets/game.riv', riveFactory: Factory.rive, ); final file = await loader.file(); final artboard = file.defaultArtboard(); if (artboard != null) { final vmi = file.createDefaultViewModelInstance(artboard); } ``` -------------------------------- ### RiveWidget Alignment Property Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget.md Specifies how the artboard aligns within the available space. Examples include center, topLeft, and bottomRight. ```dart final Alignment alignment ``` -------------------------------- ### Build rive_native Libraries for Testing Source: https://github.com/rive-app/rive-flutter/blob/master/README.md Optionally build the rive_native libraries if you prefer to compile them yourself for testing purposes. This command is similar to the general build command. ```bash dart run rive_native:setup --verbose --clean --build --platform macos ``` -------------------------------- ### Load Rive File using FileLoader (Recommended) Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Recommended method for loading Rive files, especially from assets. It provides caching and asynchronous loading capabilities. Remember to dispose of the loader when done. ```dart final loader = FileLoader.fromAsset( 'assets/animation.riv', riveFactory: Factory.rive, ); // Load asynchronously final file = await loader.file(); // Check if already loaded if (loader.isFileAvailable) { final cachedFile = loader.fileSync; } // Clean up loader.dispose(); ``` -------------------------------- ### File Loading Methods Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Methods for loading Rive files from different sources. ```APIDOC ## File Loading ### `File.asset()` #### Description Loads a Rive file from a Flutter asset. ### `File.url()` #### Description Loads a Rive file from a network URL. ### `FileLoader.file()` #### Description Retrieves a cached Rive file using `FileLoader`. ``` -------------------------------- ### Handle RiveArtboardException Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/errors.md Example of how to catch and handle a RiveArtboardException when an artboard is not found. This is useful for gracefully managing errors during Rive animation initialization. ```dart try { final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byName('NonExistent'), ); } on RiveArtboardException catch (e) { print('Artboard error: ${e.message}'); } ``` -------------------------------- ### Triggering ViewModel Actions Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Fire trigger events on a ViewModelInstance. Use the 'trigger' method to get a trigger object and then call 'fire()'. ```dart // Fire trigger events if (vmi.trigger('Jump') case var trigger?) { trigger.fire(); } if (vmi.trigger('Attack') case var trigger?) { trigger.fire(); } ``` -------------------------------- ### ArtboardSelector.byDefault() Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Creates a selector that chooses the default artboard of the file. ```APIDOC ## ArtboardSelector.byDefault() ### Description Creates a selector that chooses the default artboard of the file. ### Method Factory ### Returns `ArtboardDefault` — A selector for the default artboard ### Usage Example ```dart final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byDefault(), ); ``` ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/rive-app/rive-flutter/blob/master/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the application target. This can be removed if the application requires custom build configurations. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Get Property Value Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Safely retrieve the value of a number property. The `case` statement ensures the property exists before accessing its value. ```dart if (vmi.number('Health') case var health?) { double currentHealth = health.value; } ``` -------------------------------- ### Handle RiveDataBindException in Usage Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/errors.md Example of catching RiveDataBindException during data binding operations. Use this to gracefully handle binding failures and inform the user. ```dart try { final vmi = controller.dataBind(DataBind.byName('PlayerState')); } on RiveDataBindException catch (e) { print('Data binding failed: ${e.message}'); // Show error to user, disable data-dependent features } ``` -------------------------------- ### Create Basic Rive Controller Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Instantiate a basic controller for a Rive animation using a loaded file. This controller will manage the playback of the default artboard and state machine. ```dart final controller = RiveWidgetController(file); ``` -------------------------------- ### Access Boolean Properties in Rive Flutter Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Illustrates how to get, set, and listen to boolean properties of a Rive artboard. Use the `boolean()` method for boolean properties. ```dart vmi.boolean('PropertyName')?.value = true; vmi.boolean('PropertyName')?.addListener(callback); ``` -------------------------------- ### ViewModel Instance Creation Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/types.md Provides methods for creating instances of view models defined in a Rive file. ```dart class ViewModel { String? name; // Create instances ViewModelInstance? createDefaultInstance() ViewModelInstance? createInstance() ViewModelInstance? createInstanceByName(String name) ViewModelInstance? createInstanceByIndex(int index) } ``` -------------------------------- ### ArtboardSelector.byName(String name) Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Creates a selector that chooses the artboard with the specified name. ```APIDOC ## ArtboardSelector.byName(String name) ### Description Creates a selector that chooses the artboard with the specified name. ### Method Factory ### Parameters #### Path Parameters - **name** (String) - Required - The name of the artboard to load ### Returns `ArtboardNamed` — A selector for the named artboard ### Throws `RiveArtboardException` (in controller) if no artboard with the given name exists ### Usage Example ```dart final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byName('MainMenu'), ); ``` ``` -------------------------------- ### Synchronously Get Rive File Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/file-loader.md Returns the Rive file synchronously if it has already been loaded and cached. For loaders initiated with a URL or asset, this will return null until the file is loaded. ```dart final loader = FileLoader.fromFile(riveFile, riveFactory: Factory.rive); final cachedFile = loader.fileSync; // Returns immediately with the file final urlLoader = FileLoader.fromUrl( 'https://example.com/animation.riv', riveFactory: Factory.rive, ); final sync = urlLoader.fileSync; // Returns null until file() completes ``` -------------------------------- ### FileLoader.fromUrl Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/file-loader.md Creates a FileLoader instance to load a Rive file from a network URL. It requires the URL and a Rive factory for decoding. ```APIDOC ## FileLoader.fromUrl ### Description Creates a file loader that loads a Rive file from a network URL. ### Method Constructor ### Parameters #### Path Parameters - **url** (String) - Required - The URL to fetch the Rive file from - **riveFactory** (Factory) - Required - The Rive factory to use for decoding (either `Factory.rive` or `Factory.flutter`) ### Request Example ```dart final fileLoader = FileLoader.fromUrl( 'https://example.com/animation.riv', riveFactory: Factory.rive, ); ``` ``` -------------------------------- ### SharedRenderTexture dispose() Method Usage Example Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/shared-texture.md Releases the underlying native texture and stops all painters. Call this method when the shared texture is no longer needed to prevent memory leaks. ```dart @override void dispose() { _sharedTexture.dispose(); super.dispose(); } ``` -------------------------------- ### Dart API Signature Formats Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/README.md Illustrates common Dart syntax for API signatures including constructors, methods, getters, setters, and factory methods. ```dart // Constructor ClassName(Type param, {required Type requiredNamed}) // Method ReturnType methodName(Type param) => ... // Property getter Type get propertyName => ... // Property setter set propertyName(Type value) => ... // Factory method factory ClassName.factoryName() => ... ``` -------------------------------- ### Create RiveWidgetController Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-controller.md Instantiate a RiveWidgetController with a Rive File, optionally specifying the artboard and state machine by name or index. Ensure the Rive file is loaded correctly. ```dart final riveFile = await File.asset( 'assets/animation.riv', riveFactory: Factory.rive, ); final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byName('MainArtboard'), stateMachineSelector: StateMachineSelector.byIndex(0), ); ``` -------------------------------- ### Add Dependency Libraries and Include Directories Source: https://github.com/rive-app/rive-flutter/blob/master/example/windows/runner/CMakeLists.txt Links against necessary Flutter libraries and adds include directories for the application. Add any application-specific dependencies here. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Access Number Properties in Rive Flutter Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Demonstrates how to get, set, and listen to changes in number properties of a Rive artboard. Use the `number()` method to access properties by name. ```dart vmi.number('PropertyName')?.value = 100; vmi.number('PropertyName')?.addListener(callback); vmi.number('PropertyName')?.valueStream.listen((v) => ...); ``` -------------------------------- ### FileLoader.fromFile Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/file-loader.md Creates a FileLoader instance with an already loaded Rive File object. It requires the File object and a Rive factory for decoding. ```APIDOC ## FileLoader.fromFile ### Description Creates a file loader with an already-loaded Rive `File` instance. ### Method Constructor ### Parameters #### Path Parameters - **file** (File) - Required - An already-loaded Rive File instance - **riveFactory** (Factory) - Required - The Rive factory to use for decoding (either `Factory.rive` or `Factory.flutter`) ### Request Example ```dart final fileLoader = FileLoader.fromFile( riveFile, riveFactory: Factory.rive, ); ``` ``` -------------------------------- ### Create Rive Controller by Artboard and State Machine Index Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Create a controller by specifying the index of the desired artboard and state machine. Use this when names are not available or when referring to animations by their order. ```dart final controller = RiveWidgetController( file, artboardSelector: ArtboardSelector.byIndex(0), stateMachineSelector: StateMachineSelector.byIndex(1), ); ``` -------------------------------- ### StateMachineSelector.byDefault() Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Creates a selector that chooses the default state machine of the artboard. This is useful when an artboard has only one state machine or when you want to explicitly use the default one. ```APIDOC ## StateMachineSelector.byDefault() ### Description Creates a selector that chooses the default state machine of the artboard. ### Method Factory Method ### Returns `StateMachineDefault` — A selector for the default state machine ### Usage Example ```dart final controller = RiveWidgetController( riveFile, stateMachineSelector: StateMachineSelector.byDefault(), ); ``` ``` -------------------------------- ### DataBind.byInstance(ViewModelInstance viewModelInstance) Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Creates a data binding that uses an already-created view model instance. This method requires a pre-existing ViewModelInstance. Throws RiveDataBindException if the instance cannot be bound to the state machine. ```APIDOC ## DataBind.byInstance(ViewModelInstance viewModelInstance) ### Description Creates a data binding that uses an already-created view model instance. ### Method `static DataBind byInstance(ViewModelInstance viewModelInstance)` ### Parameters #### Path Parameters - **viewModelInstance** (ViewModelInstance) - Required - An already-created view model instance ### Returns `BindByInstance` — A binding strategy using the provided instance. ### Throws `RiveDataBindException` (in controller.dataBind) if the instance cannot be bound to the state machine. ### Usage Example ```dart // Create instance elsewhere final vmi = file.createDefaultViewModelInstance(artboard); // Use the instance later final boundVmi = controller.dataBind(DataBind.byInstance(vmi)); ``` ``` -------------------------------- ### Rive Widget Loading with Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-builder.md Shows how to use RiveWidgetBuilder with data binding for dynamic Rive animations. Includes state management for loading and interaction. ```dart class RewardsScreen extends StatefulWidget { @override State createState() => _RewardsScreenState(); } class _RewardsScreenState extends State { late final FileLoader _loader; @override void initState() { super.initState(); _loader = FileLoader.fromAsset( 'assets/rewards.riv', riveFactory: Factory.rive, ); } @override void dispose() { _loader.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return RiveWidgetBuilder( fileLoader: _loader, dataBind: DataBind.auto(), artboardSelector: ArtboardSelector.byName('RewardBoard'), onLoaded: (state) { print('File loaded and controller ready'); }, onFailed: (error, stackTrace) { print('Failed to load: $error\n$stackTrace'); }, builder: (context, state) => switch (state) { RiveLoading() => const Center( child: CircularProgressIndicator(), ), RiveLoaded(:final controller, :final viewModelInstance) => Stack( children: [ RiveWidget(controller: controller), Positioned( bottom: 20, right: 20, child: ElevatedButton( onPressed: () { if (viewModelInstance?.trigger('claim') case var trigger?) { trigger.fire(); } }, child: const Text('Claim Reward'), ), ), ], ), RiveFailed(:final error) => ErrorWidget.withDetails( message: error.toString(), error: FlutterError(error.toString()), ), }, ); } } ``` -------------------------------- ### Multiple Data Bindings in Rive Flutter Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md This example illustrates how to bind to multiple view models simultaneously from different Rive animations or different view models within the same animation. It shows independent interaction with properties of each bound view model. ```dart // Bind multiple view models final playerState = controller.dataBind(DataBind.byName('PlayerState')); final enemyState = controller.dataBind(DataBind.byName('EnemyState')); // Interact with both independently playerState.number('Health')?.value = 100; enemyState.number('Health')?.value = 50; ``` -------------------------------- ### Flutter Data Binding for Real-Time Animation Updates Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/patterns.md This example demonstrates how to bind application state (e.g., health) to animation properties using Rive's data binding. It synchronizes a LinearProgressIndicator and text display with the animation's 'Health' parameter, updating dynamically when damage is taken or health is restored. Ensure 'assets/game.riv' is included in your project's assets. ```dart class DataBindingExample extends StatefulWidget { @override State createState() => _DataBindingExampleState(); } class _DataBindingExampleState extends State { late FileLoader _loader; late RiveWidgetController _controller; late ViewModelInstance _vmi; File? _file; double _health = 100; @override void initState() { super.initState(); _init(); } Future _init() async { _loader = FileLoader.fromAsset( 'assets/game.riv', riveFactory: Factory.rive, ); _file = await _loader.file(); _controller = RiveWidgetController(_file!); _vmi = _controller.dataBind(DataBind.auto()); // Update animation when health changes _syncHealth(); setState(() {}); } void _syncHealth() { _vmi.number('Health')?.value = _health; } void _takeDamage(double amount) { setState(() { _health = (_health - amount).clamp(0, 100); }); _syncHealth(); } void _heal(double amount) { setState(() { _health = (_health + amount).clamp(0, 100); }); _syncHealth(); } @override void dispose() { _vmi.dispose(); _loader.dispose(); _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return _file == null ? const CircularProgressIndicator() : Column( children: [ Expanded( child: RiveWidget(controller: _controller), ), Padding( padding: const EdgeInsets.all(16), child: Column( children: [ LinearProgressIndicator( value: _health / 100, minHeight: 10, ), const SizedBox(height: 8), Text('Health: ${_health.toStringAsFixed(0)}'), const SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( onPressed: () => _takeDamage(10), style: ElevatedButton.styleFrom( backgroundColor: Colors.red, ), child: const Text('Damage (10)'), ), ElevatedButton( onPressed: () => _heal(10), style: ElevatedButton.styleFrom( backgroundColor: Colors.green, ), child: const Text('Heal (10)'), ), ], ), ], ), ), ], ); } } ``` -------------------------------- ### Dynamic Artboard Selection Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Shows how to dynamically select an artboard based on a condition, defaulting to the 'byDefault' selector if no name is provided. ```dart ArtboardSelector selectArtboard(String? name) { if (name == null) { return ArtboardSelector.byDefault(); } return ArtboardSelector.byName(name); } final controller = RiveWidgetController( riveFile, artboardSelector: selectArtboard(userChoice), ); ``` -------------------------------- ### State Machine Access Methods Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Methods for accessing State Machines from an Artboard. ```APIDOC ## State Machine Access ### `Artboard.defaultStateMachine()` #### Description Retrieves the default State Machine from an Artboard. Returns: `StateMachine?` ### `Artboard.stateMachine(String name)` #### Description Retrieves a specific State Machine by its name from an Artboard. Parameters: - **name** (String) - The name of the State Machine to retrieve. Returns: `StateMachine?` ### `Artboard.stateMachineAt(int index)` #### Description Retrieves a specific State Machine by its index from an Artboard. Parameters: - **index** (int) - The index of the State Machine to retrieve. Returns: `StateMachine?` ``` -------------------------------- ### Load Rive File from URL Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/types.md Loads a Rive file from a URL. Requires a factory for Rive rendering. ```dart class File { // Loads from URL static Future url( String url, { required Factory riveFactory, } ) ``` -------------------------------- ### Basic Rive Widget Loading Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget-builder.md Demonstrates the basic pattern for loading a Rive animation using RiveWidgetBuilder. Handles loading, success, and error states. ```dart class MyRiveScreen extends StatelessWidget { @override Widget build(BuildContext context) { final loader = FileLoader.fromAsset( 'assets/animation.riv', riveFactory: Factory.rive, ); return RiveWidgetBuilder( fileLoader: loader, builder: (context, state) => switch (state) { RiveLoading() => const Center( child: CircularProgressIndicator(), ), RiveLoaded(:final controller) => RiveWidget( controller: controller, ), RiveFailed(:final error) => Center( child: Text('Error: $error'), ), }, ); } } ``` -------------------------------- ### Interactive Animation with Data Binding Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/OVERVIEW.md Demonstrates how to bind data to a Rive animation, set properties, fire triggers, and listen to changes. This allows for dynamic control and interaction with animations. ```dart final controller = RiveWidgetController(file); final vmi = controller.dataBind(DataBind.auto()); // Set properties vmi.number('Health')?.value = 100; // Fire triggers vmi.trigger('Jump')?.fire(); // Listen to changes vmi.number('Score')?.addListener(() { print('Score: ${vmi.number('Score')?.value}'); }); ``` -------------------------------- ### Create Data Binding by Instance Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/data-binding.md Creates a data binding that uses an already-created view model instance. Requires a pre-existing ViewModelInstance. ```dart static DataBind byInstance(ViewModelInstance viewModelInstance) => BindByInstance(viewModelInstance) ``` -------------------------------- ### Create Default Artboard Selector Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Creates a selector that chooses the default artboard of the file. Use this when you want to load the first artboard in the Rive file. ```dart factory ArtboardSelector.byDefault() => const ArtboardDefault() ``` ```dart final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byDefault(), ); ``` -------------------------------- ### Fit Options Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md These options control how the animation fits within its bounds. Use `Fit.contain` for safe defaults, `Fit.cover` for full-screen backgrounds, `Fit.fill` when distortion is acceptable, `Fit.fitWidth` or `Fit.fitHeight` for aspect-ratio-preserving layouts, `Fit.scaleDown` for responsive designs, and `Fit.layout` for dynamic sizing. ```dart Fit.contain ``` ```dart Fit.cover ``` ```dart Fit.fill ``` ```dart Fit.fitWidth ``` ```dart Fit.fitHeight ``` ```dart Fit.scaleDown ``` ```dart Fit.layout ``` -------------------------------- ### Load and Display Simple Animation Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/OVERVIEW.md Loads a Rive animation from assets and displays it using RiveWidget. Ensure the Rive file is in the assets folder and configured in pubspec.yaml. ```dart final file = await File.asset('assets/animation.riv', riveFactory: Factory.rive); final controller = RiveWidgetController(file); return RiveWidget(controller: controller); ``` -------------------------------- ### Artboard Access Methods Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/INDEX.md Methods for accessing Artboards from a loaded Rive file. ```APIDOC ## Artboard Access ### `File.defaultArtboard()` #### Description Retrieves the default Artboard from a Rive file. Returns: `Artboard?` ### `File.artboard(String name)` #### Description Retrieves a specific Artboard by its name from a Rive file. Parameters: - **name** (String) - The name of the Artboard to retrieve. Returns: `Artboard?` ### `File.artboardAt(int index)` #### Description Retrieves a specific Artboard by its index from a Rive file. Parameters: - **index** (int) - The index of the Artboard to retrieve. Returns: `Artboard?` ``` -------------------------------- ### Basic RiveWidget Usage Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-widget.md This is the most basic way to use RiveWidget. Ensure the controller is properly initialized. ```dart @override Widget build(BuildContext context) { return RiveWidget( controller: _controller, ); } ``` -------------------------------- ### RiveFileExtension.createDefaultViewModelInstance Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/rive-extensions.md Creates a default view model instance for a given artboard from a Rive file. ```APIDOC ## createDefaultViewModelInstance() ### Description Creates a default view model instance for the given artboard. ### Method Signature `ViewModelInstance? createDefaultViewModelInstance(Artboard artboard)` ### Parameters #### Path Parameters - **artboard** (Artboard) - Required - The artboard to create the view model instance for ### Returns `ViewModelInstance?` - The created view model instance, or `null` if the artboard has no default view model. ### Behavior Gets the default view model from the file and creates a default instance for the specified artboard. ### Usage Example ```dart final file = await File.asset( 'assets/animation.riv', riveFactory: Factory.rive, ); final artboard = file.defaultArtboard(); if (artboard != null) { final vmi = file.createDefaultViewModelInstance(artboard); if (vmi != null) { // Use the view model instance vmi.number('Health')?.value = 100; } } ``` ``` -------------------------------- ### Create Rive Controller with Specific Artboard and State Machine Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/quick-reference.md Create a controller that targets a specific artboard and state machine within the Rive file by their names. This allows for precise control over which animation plays. ```dart final controller = RiveWidgetController( file, artboardSelector: ArtboardSelector.byName('MainBoard'), stateMachineSelector: StateMachineSelector.byName('PlayerAnimation'), ); ``` -------------------------------- ### Create Default State Machine Selector Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Use this factory method to create a selector for the artboard's default state machine. It's suitable when you only have one state machine or want to use the primary one. ```dart factory StateMachineSelector.byDefault() => const StateMachineDefault() ``` ```dart final controller = RiveWidgetController( riveFile, stateMachineSelector: StateMachineSelector.byDefault(), ); ``` -------------------------------- ### ArtboardSelector.byIndex(int index) Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Creates a selector that chooses the artboard at the specified zero-based index. ```APIDOC ## ArtboardSelector.byIndex(int index) ### Description Creates a selector that chooses the artboard at the specified zero-based index. ### Method Factory ### Parameters #### Path Parameters - **index** (int) - Required - The zero-based index of the artboard ### Returns `ArtboardAtIndex` — A selector for the indexed artboard ### Throws `RiveArtboardException` (in controller) if the index is out of bounds ### Usage Example ```dart final controller = RiveWidgetController( riveFile, artboardSelector: ArtboardSelector.byIndex(0), ); ``` ``` -------------------------------- ### Define Executable Target Source: https://github.com/rive-app/rive-flutter/blob/master/example/windows/runner/CMakeLists.txt Defines the main executable for the Windows application. Ensure BINARY_NAME is consistent with the top-level CMakeLists.txt for `flutter run` to function correctly. Add any new source files for the application here. ```cmake add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) ``` -------------------------------- ### Create Indexed State Machine Selector Source: https://github.com/rive-app/rive-flutter/blob/master/_autodocs/selectors.md Use this factory method to create a selector for a state machine based on its zero-based index. This is helpful when you know the order of state machines but not their names, or for programmatic selection. ```dart factory StateMachineSelector.byIndex(int index) => StateMachineAtIndex(index) ``` ```dart final controller = RiveWidgetController( riveFile, stateMachineSelector: StateMachineSelector.byIndex(0), ); ```