我正试图在Flutter中重新播放Flare动画。完成后不动画循环动画。我希望动画能够按需播放,同样的动画。
当我在动画之间切换时,只需交换字符串并调用setState就可以正常工作。有一个简单的方法来做到这一点。
这就是我目前正在做的事情。
class _FlareDemoState extends State<FlareDemo> {
String animationToPlay = 'activate';
@override
Widget build(BuildContext context) {
print('Animation to play: $animationToPlay');
return Scaffold(
backgroundColor: Colors.purple,
body: GestureDetector(
onTap: () {
setState(() {
});
},
child: FlareActor('assets/button-animation.flr',
animation: animationToPlay)));
}
}
点击动画时会生成我的日志
I/flutter (18959): Animation to play: activate
I/flutter (18959): Animation to play: activate
I/chatty (18959): uid=10088(com.example.flare_tutorial) Thread-2 identical 2 lines
I/flutter (18959): Animation to play: activate
I/flutter (18959): Animation to play: activate
I/chatty (18959): uid=10088(com.example.flare_tutorial) Thread-2 identical 7 lines
I/flutter (18959): Animation to play: activate
I/flutter (18959): Animation to play: activate
Reloaded 2 of 495 libraries in 672ms.
I/flutter (18959): Animation to play: activate
一切都被调用,它第一次播放,但之后动画不重播。
更简洁的方法是使用自定义FlareController。有一个具体的FlareControls实现很适合这个用例。
class _MyHomePageState extends State<MyHomePage> {
// Store a reference to some controls for the Flare widget
final FlareControls controls = FlareControls();
void _playSuccessAnimation() {
// Use the controls to trigger an animation.
controls.play("success");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FlareActor("assets/Teddy.flr",
animation: "idle",
fit: BoxFit.contain,
alignment: Alignment.center,
// Make sure you use the controls with the Flare Actor widget.
controller: controls),
floatingActionButton: FloatingActionButton(
onPressed: _playSuccessAnimation,
tooltip: 'Play',
child: Icon(Icons.play_arrow),
),
);
}
}
请注意,此示例还播放循环的空闲背景动画。对FlareControls.play的任何调用都会在这个背景空闲动画中混合传入的动画。如果你不想/需要背景动画,你只需省略动画:“idle”参数。
基于@Eugene的答案,我提出了一个临时解决方案。我将值设置为空,启动计时器50毫秒,然后将值设置回我想要再次播放的动画。
class _FlareDemoState extends State<FlareDemo> {
String animationToPlay = 'activate';
@override
Widget build(BuildContext context) {
print('Animation to play: $animationToPlay');
return Scaffold(
backgroundColor: Colors.purple,
body: GestureDetector(
onTap: () {
_setAnimationToPlay('activate');
},
child: FlareActor('assets/button-animation.flr',
animation: animationToPlay)));
}
}
void _setAnimationToPlay(String animation) {
if (animation == _animationToPlay) {
_animationToPlay = '';
Timer(const Duration(milliseconds: 50), () {
setState(() {
_animationToPlay = animation;
});
});
} else {
_animationToPlay = animation;
}
}
这是一个混乱的解决方法,但它完成了工作。感谢@Eugene种植种子。