@kohjakob的答案有效,但它不是一个可重用的小部件。
所以我创建了AnimatedCollapse
。它基于其他Animated[...]
小部件的风格,并使用SizeTransition
,监听collapsed
属性的任何更改以反向或前进动画。
class AnimatedCollapse extends StatefulWidget {
const AnimatedCollapse({
Key? key,
this.child,
required this.collapsed,
this.axis = Axis.vertical,
this.axisAlignment = 0.0,
this.curve = Curves.linear,
required this.duration,
this.reverseDuration,
}) : super(key: key);
final Widget? child;
final bool collapsed;
final Axis axis;
final double axisAlignment;
final Curve curve;
final Duration duration;
final Duration? reverseDuration;
@override
_AnimatedCollapseState createState() => _AnimatedCollapseState();
}
class _AnimatedCollapseState extends State<AnimatedCollapse> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: widget.duration,
reverseDuration: widget.reverseDuration,
);
_animation = CurvedAnimation(
parent: _controller,
curve: widget.curve,
);
if (!widget.collapsed) {
_controller.forward();
}
}
@override
void didUpdateWidget(covariant AnimatedCollapse oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.collapsed != oldWidget.collapsed) {
if (widget.collapsed) {
_controller.reverse();
} else {
_controller.forward();
}
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizeTransition(
sizeFactor: _animation,
axis: widget.axis,
axisAlignment: widget.axisAlignment,
child: widget.child,
);
}
}
expansion_tile.dart
源文件 - 它使用了Align.heightFactor
,这是一个小技巧。 - pskink