Flutter项目接入Rive动画无法播放仅显示静态内容如何解决
问题原因与解决方案
你遇到的问题核心原因是代码中传入的动画名称和Rive文件内实际定义的动画名称不匹配,Rive控制器找不到对应动画时就会停在首帧显示静态内容,你之前尝试的idle、center都不是目标动画的正确命名。
具体解决步骤
- 第一步:确认Rive文件内的动画名称
用Rive桌面端应用打开你导出的.riv文件,在左侧动画面板可查看所有已导出动画的准确名称,名称的大小写、空格都要完全匹配才能正常加载。你提到的移动卡车动效内置的动画名称为Animation 1,直接替换代码中的动画名称即可生效。 - 第二步:添加调试逻辑避免名称匹配错误
你可以在加载Rive文件后打印当前画板所有可用的动画名称,不需要人工猜测名称,示例代码如下:rootBundle.load('assets/rive/new.riv').then( (data) async { final file = RiveFile.import(data); final artboard = file.mainArtboard; // 控制台打印所有可用动画名称,用于调试 for (var animation in artboard.animations) { debugPrint('可用动画名称:${animation.name}'); } // 替换为控制台打印的正确动画名称即可 artboard.addController(_controller = SimpleAnimation('Animation 1')); setState(() => _riveArtboard = artboard); }, ); - 第三步:其他可排查的边界问题
如果你自己制作的Rive动效按上述方法还是无法播放,导出.riv文件时要确认你勾选了需要导出的动画选项,未勾选的动画不会被打包到文件中,也会出现只显示静态内容的情况。
你当前可以正常显示静态帧,说明pubspec.yaml中的资源路径配置是正确的,无需排查路径问题。
修改后可直接运行的完整代码
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:rive/rive.dart'; class ExampleAnimation extends StatefulWidget { const ExampleAnimation({Key? key}) : super(key: key); @override _ExampleAnimationState createState() => _ExampleAnimationState(); } class _ExampleAnimationState extends State<ExampleAnimation> { void _togglePlay() { if (_controller == null) { return; } setState(() => _controller!.isActive = !_controller!.isActive); } bool get isPlaying => _controller?.isActive ?? false; Artboard? _riveArtboard; RiveAnimationController? _controller; @override void initState() { super.initState(); rootBundle.load('assets/rive/new.riv').then( (data) async { final file = RiveFile.import(data); final artboard = file.mainArtboard; // 打印所有可用动画 for (var anim in artboard.animations) { debugPrint('可用动画:${anim.name}'); } artboard.addController(_controller = SimpleAnimation('Animation 1')); setState(() => _riveArtboard = artboard); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Animation Example'), ), body: Center( child: _riveArtboard == null ? const SizedBox() : Rive(artboard: _riveArtboard!), ), floatingActionButton: FloatingActionButton( onPressed: _togglePlay, tooltip: isPlaying ? 'Pause' : 'Play', child: Icon( isPlaying ? Icons.pause : Icons.play_arrow, ), ), ); } }
内容的提问来源于stack exchange,提问作者umanga shrestha
相关产品推荐
相关产品推荐

