flutter 播放动图
时间: 2024-06-11 20:02:22 浏览: 25
可以使用Flutter中的两种方法播放动画。
1. 通过使用Flutter自带的动画库:Flutter中的动画库可以通过控制Animation对象,将动画分为多个帧,并通过AnimationController控制动画的执行时间,以及动画执行的方向和速度。以下是一个简单的使用Flutter动画库播放动画的例子[^1]:
```dart
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
class MyAnimatedWidget extends StatefulWidget {
@override
_MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}
class _MyAnimatedWidgetState extends State<MyAnimatedWidget>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = Tween<double>(begin: 0, end: 1).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget child) {
return Transform.scale(
scale: _animation.value,
child: child,
);
},
child: Image.asset('assets/images/animation.gif'),
),
);
}
}
```
2. 通过使用第三方库,如SVGAPlayer-Flutter:这是一个轻量级的动画渲染库,可以通过Flutter CustomPainter原生渲染动画,为您带来高性能,低成本的动画体验。以下是一个简单的使用SVGAPlayer-Flutter播放动画的例子。首先需要在pubspec.yaml文件中添加依赖[^2]:
```yaml
dependencies:
svga_player: ^1.2.1
```
使用如下代码播放动画:
```dart
import 'package:flutter/material.dart';
import 'package:svga_player/svga_player.dart';
class SVGAPlayerWidget extends StatefulWidget {
@override
_SVGAPlayerWidgetState createState() => _SVGAPlayerWidgetState();
}
class _SVGAPlayerWidgetState extends State<SVGAPlayerWidget> {
SVGAAnimationController animationController;
@override
void initState() {
super.initState();
animationController = SVGAAnimationController.network(
'https://github.com/yyued/SVGA-Samples/raw/master/EmptyState.svga')
..repeat();
}
@override
void dispose() {
animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: SizedBox(
width: 200,
height: 200,
child: SVGAPlayer(
animationController: animationController,
),
),
);
}
}
```