Git 命令行教程及实例教程,深入理解Flutter动画原理
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,
);
animation = Tween<double>(begin: 0, end: 300).animate(controller)
..addListener(() => setState(() {}));
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('动画示例')),
body: Center(
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: animation.value,
width: animation.value,
child: FlutterLogo(),
),
),
);
}
}
这段代码展示了如何在Flutter应用中创建和运行一个简单的动画。通过使用AnimationController
和Tween
,我们创建了一个从0到300的线性动画。在initState
方法中,我们启动了这个动画并将其添加到监听器中,以便每次动画值更新时,都会调用setState
方法来重新构建UI。这是实现动画效果的一种常见模式。
评论已关闭