Question #344MediumWidgets & UI

What is the purpose of the AnimatedSwitcher widget in Flutter?

#widget#animation#animatedswitcher

Answer

Overview

text
AnimatedSwitcher
animates the transition when switching between different widgets. When its child changes, the old child animates out and the new child animates in.


Basic Usage

dart
class CounterWidget extends StatefulWidget {
  
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _count = 0;

  
  Widget build(BuildContext context) {
    return Column(
      children: [
        AnimatedSwitcher(
          duration: Duration(milliseconds: 300),
          child: Text(
            '$_count',
            key: ValueKey<int>(_count), // ✅ Key required for detection
            style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
          ),
        ),
        ElevatedButton(
          onPressed: () => setState(() => _count++),
          child: Text('Increment'),
        ),
      ],
    );
  }
}

Why the Key Matters

dart
// ❌ Without key — AnimatedSwitcher won't detect the change
AnimatedSwitcher(
  duration: Duration(milliseconds: 300),
  child: Text('$_count'), // Same type, no unique key = no animation
)

// ✅ With ValueKey — detects new child, triggers animation
AnimatedSwitcher(
  duration: Duration(milliseconds: 300),
  child: Text('$_count', key: ValueKey<int>(_count)),
)

Custom Transition

dart
AnimatedSwitcher(
  duration: Duration(milliseconds: 500),
  transitionBuilder: (child, animation) {
    return ScaleTransition(scale: animation, child: child);
  },
  child: Icon(
    _isFavorite ? Icons.favorite : Icons.favorite_border,
    key: ValueKey<bool>(_isFavorite),
    color: _isFavorite ? Colors.red : Colors.grey,
  ),
)

Switching Between Different Widgets

dart
AnimatedSwitcher(
  duration: Duration(milliseconds: 400),
  child: _isLoading
      ? CircularProgressIndicator(key: ValueKey('loading'))
      : Text('Data loaded!', key: ValueKey('data')),
)

Available Transition Types

dart
// Default (FadeTransition)
AnimatedSwitcher(duration: Duration(milliseconds: 300), child: ...)

// Scale
transitionBuilder: (child, animation) => ScaleTransition(scale: animation, child: child)

// Slide
transitionBuilder: (child, animation) => SlideTransition(
  position: Tween(begin: Offset(1, 0), end: Offset.zero).animate(animation),
  child: child,
)

// Rotation
transitionBuilder: (child, animation) => RotationTransition(turns: animation, child: child)

AnimatedSwitcher vs AnimatedBuilder

FeatureAnimatedSwitcherAnimatedBuilder
Use caseSwapping between widgetsCustom animations on a single widget
TriggerChild widget changesAnimation controller value changes
Key required✅ Yes (for same widget type)❌ No

Best for: Tab/page transitions, loading→content switches, like/unlike button animations.