Animation<T>.fromValueListenable constructor

Animation<T>.fromValueListenable(
  1. ValueListenable<T> listenable, {
  2. ValueListenableTransformer<T>? transformer,
})

Create a new animation from a ValueListenable.

The returned animation will always have an animations status of AnimationStatus.forward. The value of the provided listenable can be optionally transformed using the transformer function.

This constructor can be used to replace instances of ValueListenableBuilder widgets with a corresponding animated widget, like a FadeTransition.

Before:

link
Widget build(BuildContext context) {
  return ValueListenableBuilder<double>(
    valueListenable: _scrollPosition,
    builder: (BuildContext context, double value, Widget? child) {
      final double opacity = (value / 1000).clamp(0, 1);
      return Opacity(opacity: opacity, child: child);
    },
    child: const ColoredBox(
      color: Colors.red,
      child: Text('Hello, Animation'),
    ),
  );
}

After:
link
Widget build2(BuildContext context) {
  return FadeTransition(
    opacity: Animation<double>.fromValueListenable(_scrollPosition, transformer: (double value) {
      return (value / 1000).clamp(0, 1);
    }),
    child: const ColoredBox(
      color: Colors.red,
      child: Text('Hello, Animation'),
    ),
  );
}

Implementation

factory Animation.fromValueListenable(ValueListenable<T> listenable, {
  ValueListenableTransformer<T>? transformer,
}) = _ValueListenableDelegateAnimation<T>;