class
RiveDemo extends StatefulWidget {
const RiveDemo({Key? key}) :
super
(key: key);
@override
State<RiveDemo> createState()
=
> _RiveDemoState();
}
class
_RiveDemoState extends State<RiveDemo> {
/
/
/
状态机控制器
StateMachineController? controller;
/
/
/
控制输入数值
SMIInput<double>? valueController;
/
/
/
画板,配合Rive widget 使用,展示动画效果。
Artboard? riveArtboard;
Timer? timer;
@override
void initState() {
super
.initState();
/
/
加载
rootBundle.load(
'asset/rives/rive_demo.riv'
).then((value) async {
final
file
=
RiveFile.
import
(value);
final artboard
=
file
.mainArtboard;
/
/
1
controller
=
StateMachineController.fromArtboard(artboard,
'TreeMachine'
);
if
(controller !
=
null) {
setState(() {
artboard.addController(controller!);
/
/
2
valueController
=
controller!.findInput(
'input'
);
valueController!.value
=
-
4
;
});
}
riveArtboard
=
artboard;
});
}
@override
void dispose() {
controller?.dispose();
stopAnimation();
super
.dispose();
}
@override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(
title: const Text(
'Rive Demo'
),
),
backgroundColor: Colors.white,
body: Center(
child: riveArtboard
=
=
null ? const CircularProgressIndicator() : Rive(artboard: riveArtboard!),
),
floatingActionButton: SizedBox(
height:
50
,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
startAnimation();
},
child: const Text(
'start'
),
),
TextButton(
onPressed: () {
stopAnimation();
},
child: const Text(
'stop'
),
),
TextButton(
onPressed: () {
resetAnimation();
},
child: const Text(
'reset'
),
),
],
),
),
);
}
/
/
/
开始动画
void startAnimation() {
if
(timer !
=
null) {
return
;
}
timer
=
Timer.periodic(const Duration(milliseconds:
60
), (timer) {
valueController?.value
+
=
0.5
;
});
}
/
/
/
停止动画
void stopAnimation() {
timer?.cancel();
timer
=
null;
}
/
/
/
重置动画
void resetAnimation() {
stopAnimation();
valueController?.value
=
0
;
}
}