How to get current color property of a widget?

Viewed 231

I am trying to build a widget which has a changing colors. For example, it starts with white and animate the color slowly over time to become red. Then, I need to get its color when the user press a button. Now, I am trying to achieve this by using AnimatedContainer. It does the exact animation I want. However, I can't get the color property at specific time(e.g pressing a button). Is it possible to do this using standard Flutter widgets? Or, is there any Flutter package to satisfy this need?

1 Answers

You can create your own ColorAnimation widget. ImplicitlyAnimatedWidget (AnimatedContainer uses this) you can animate a widget when a variable changes in your case a color. You will need to use a ColorTween for the transition.

With this you could create getter in the State of the animation that gives the current Color.

Here is an example implementation:

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,
      ),
    );
  }
}

With this you could get the color with:

//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;
Related