抽象类 Animation
实现类
- AnimationController
- forward 向前直行动画
- reverse 向前直行动画
- CurvedAnimation 设置动画执行速率
- Tween 设置动画执行的value范围
上面实现方式要在Listening 执行setState中执行,性能不好
优化方案: - AnimatedWidget,缺点:要继承这个类,使用麻烦。
- AnimatedBuilder
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
"/": (context) => HomePage(),
},
initialRoute: "/",
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
late AnimationController _controller;
late CurvedAnimation _curvedAnimation;
late Animation _tween;
@override
void initState() {
// TODO: implement initState
super.initState();
_controller = AnimationController(
lowerBound: 0.0,
upperBound:1.0,
vsync: this,
duration: const Duration(seconds: 1),
reverseDuration: const Duration(seconds: 1));
_curvedAnimation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
_tween = Tween(begin: 50.0, end: 100.0).animate(_curvedAnimation);
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("ts"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedBuilder(
animation: _tween,
builder: (context, child) {
return Icon(
Icons.favorite,
color: Colors.red,
size: _tween.value,
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.play_circle),
onPressed: () {
if (_controller.isAnimating) {
_controller.stop();
} else if (_controller.status == AnimationStatus.forward){
_controller.forward();
} else if (_controller.status == AnimationStatus.reverse) {
_controller.reverse();
} else if (_controller.status == AnimationStatus.dismissed) {
_controller.forward();
} else if (_controller.status == AnimationStatus.completed) {
_controller.reverse();
}
},
),
);
}
}