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 TickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
animation = CurvedAnimation(
parent: controller,
curve: Curves.elasticInOut,
);
controller.forward();
controller.addListener(() => setState(() {}));
}
@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.0),
child: Column(
children: <Widget>[
AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
return Transform.translate(
offset: Offset(50.0 * animation.value, 0.0),
child: child,
);
},
child: FlutterLogo(size: 100.0),
),
],
),
),
),
);
}
}
这段代码使用了AnimatedBuilder来构建一个动画,这个构建器会在动画的每一帧自动重新构建其子widget,并应用新的变换。这里的变换是一个平移,根据动画的当前值(介于0和1之间)来改变logo的位置。这种方法避免了使用setState
,因此避免了不必要的widget重新构建,这对于性能优化是有益的。
评论已关闭