深入理解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(
body: Center(
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: animation.value,
width: animation.value,
child: FlutterLogo(),
),
),
);
}
}
这段代码创建了一个简单的Flutter应用,其中包含了一个动画控制器和动画对象。动画对象会在2秒内从0增加到300,控制一个Flutter徽标的大小,从而展示了Flutter中动画的基本原理。代码示例中使用了AnimationController
、Tween
和CurvedAnimation
,并展示了如何在initState
方法中启动动画。
评论已关闭