Flutter AnimatedWidget 实现动画的自动刷新
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(min: 0, max: 1, period: Duration(seconds: 2)); // 循环动画
animation = CurvedAnimation(
parent: controller,
curve: Curves.elasticInOut,
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Animated Widget Example')),
body: Center(
child: AnimatedLogo(animation: animation),
),
);
}
}
class AnimatedLogo extends AnimatedWidget {
const AnimatedLogo({Key key, Animation<double> animation})
: super(key: key, listenable: animation);
@override
Widget build(BuildContext context) {
final Animation<double> animation = listenable;
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: 200.0 * animation.value,
width: 200.0 * animation.value,
child: FlutterLogo(),
);
}
}
这段代码定义了一个有状态的HomePage
小部件,它使用AnimationController
来控制一个动画。动画通过CurvedAnimation
实现,并通过AnimatedLogo
小部件在Flutter的标志上显示。AnimatedLogo
是一个AnimatedWidget
,它会在每次动画更新时重新构建,以反映当前动画状态。这个例子展示了如何使用AnimationController
和CurvedAnimation
来创建一个循环的动画序列,并且如何将其集成到Flutter应用中。
评论已关闭