一个使用TweenAnimationBuilder自定义封装动画控件的例子,不需要自己声明AnimationController.
来自官网例子的改造
import 'package:flutter/material.dart';
void main() => runApp(const TweenAnimationBuilderExampleApp());
class TweenAnimationBuilderExampleApp extends StatelessWidget {
const TweenAnimationBuilderExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Column(
children: [
MyAnimatedWidget(
duration: Duration(seconds: 1),
icon: Icon(Icons.lock_clock),
),
MyAnimatedWidget(
duration: Duration(seconds: 2),
icon: Icon(Icons.leaderboard),
),
MyAnimatedWidget(
duration: Duration(seconds: 1),
icon: Icon(Icons.offline_bolt),
),
],
),
),
),
);
}
}
// MyAnimatedWidget
class MyAnimatedWidget extends StatefulWidget {
const MyAnimatedWidget(
{super.key, required this.duration, required this.icon});
final Duration duration;
final Icon icon;
@override
State<MyAnimatedWidget> createState() => _MyAnimatedWidgetState();
}
class _MyAnimatedWidgetState extends State<MyAnimatedWidget> {
double target = 24.0;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder(
tween: Tween<double>(begin: 0, end: target),
duration: widget.duration,
builder: (context, value, child) {
return IconButton(
iconSize: value,
onPressed: () {
setState(() {
target = target == 24.0 ? 48.0 : 24.0;
});
},
icon: child!,
);
},
child: widget.icon,
);
}
}