您可以创建自己的ColorAnimation 小部件。 ImplicitlyAnimatedWidget(AnimatedContainer 使用它)您可以在变量更改颜色时为小部件设置动画。您需要使用ColorTween 进行转换。
有了这个,你可以在动画的状态中创建 getter 来给出当前的Color。
这是一个示例实现:
class TestColor extends ImplicitlyAnimatedWidget {
const TestColor({
Key? key,
this.onTap,
this.color,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
}) : super(key: key, curve: curve, duration: duration, onEnd: onEnd);
final Color? color;
final void Function(Color? color)? onTap;
@override
AnimatedWidgetBaseState<TestColor> createState() =>
_TestColorState();
}
class _TestColorState
extends AnimatedWidgetBaseState<TestColor> {
ColorTween? _color;
Color? get color => _color?.evaluate(animation);
@override
void forEachTween(TweenVisitor<dynamic> visitor) {
_color = visitor(_color, widget.color,
(dynamic value) => ColorTween(begin: value as Color))
as ColorTween?;
}
@override
Widget build(BuildContext context) {
final Animation<double> animation = this.animation;
final Color? color = _color?.evaluate(animation);
return GestureDetector(
onTap: () => widget.onTap?.call(color),
child: Container(
color: color,
width: 100,
height: 100,
),
);
}
}
有了这个,你可以得到颜色:
//The key
final GlobalKey<_TestColorState> color = GlobalKey();
//The widget
TestColor(
key: color,
duration: const Duration(seconds: 2),
color: Colors.red,
)
//How to get the current color
color.currentState?.color;