Back to Articles

Intermediate

AnimatedDefaultTextStyle: Animating Text Style Changes

· 6 min read

AnimatedDefaultTextStyle: Animating Text Style Changes

What Is AnimatedDefaultTextStyle?

When you change a text style in Flutter (for example, enlarging and coloring the label of the selected tab), the change is applied instantly on the next frame. AnimatedDefaultTextStyle turns that change into an animation. When you give it a new style, it transitions smoothly from the old style to the new one over the duration and curve you specify.

This widget belongs to the same family as AnimatedContainer and AnimatedOpacity: implicit animation widgets. You don't need to create, start or dispose an AnimationController. Changing the target style with setState is enough.

DefaultTextStyle vs AnimatedDefaultTextStyle
On the left, DefaultTextStyle jumps instantly when the style changes; on the right, AnimatedDefaultTextStyle makes the same change with a 600 ms animation.

How Does It Work?

As the name suggests, this widget is the animated version of DefaultTextStyle. DefaultTextStyle provides a default style to the Text widgets in its subtree. When style changes, AnimatedDefaultTextStyle produces intermediate values between the old and new TextStyle using TextStyle.lerp and passes that intermediate style down the tree on every frame.

That is why the Text inside the child must not override the animated properties in its own style parameter. The style you give to Text is merged with the default style, and properties set directly on Text do not take part in the animation.

Basic Usage

class HighlightTitle extends StatefulWidget {
  const HighlightTitle({super.key});

  @override
  State<HighlightTitle> createState() => _HighlightTitleState();
}

class _HighlightTitleState extends State<HighlightTitle> {
  bool _isHighlighted = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() => _isHighlighted = !_isHighlighted),
      child: AnimatedDefaultTextStyle(
        duration: const Duration(milliseconds: 600),
        curve: Curves.easeInOutCubic,
        style: _isHighlighted
            ? const TextStyle(
                fontSize: 56,
                fontWeight: FontWeight.w800,
                letterSpacing: 2,
                color: Colors.cyan,
              )
            : const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.w400,
                letterSpacing: 0,
                color: Colors.grey,
              ),
        child: const Text('Flutter'),
      ),
    );
  }
}

A tap only flips _isHighlighted; AnimatedDefaultTextStyle handles the rest. The font size grows from 28 to 56 while the color shifts from grey to cyan, the letter spacing opens up and the text becomes bolder.

Parameters

• style (required): The target TextStyle. Changing it starts the animation. • duration (required): How long the animation takes. • curve: The easing curve. Defaults to Curves.linear. • onEnd: A callback invoked when the animation finishes. • textAlign, softWrap, overflow, maxLines: Same as their DefaultTextStyle counterparts. They are not animated; changes apply immediately. • textWidthBasis, textHeightBehavior: Advanced settings related to text measurement.

Which Properties Are Animated?

TextStyle.lerp interpolates numeric values and colors gradually. These include fontSize, color, backgroundColor, letterSpacing, wordSpacing, height, decorationColor, decorationThickness and shadows. fontWeight is interpolated as well, but how smooth the transition looks depends on which weights your font actually provides.

Properties that cannot be interpolated, such as fontFamily, fontStyle and decoration, switch abruptly at the exact midpoint of the animation (t = 0.5). For example, when going from italic to normal, the text suddenly straightens halfway through.

Tip: Fading a Shadow In Smoothly

Shadow lists are matched element by element. If one style has a shadow with no counterpart in the other, Flutter only scales that shadow: its blur and offset grow, but its color shows at full opacity from the very start. If you want the shadow to fade in together with its color, define the same number of shadows in both styles and make the color transparent on the side where it should be invisible:

// Normal style: the shadow exists but is transparent
TextStyle(
  fontSize: 28,
  color: Colors.grey,
  shadows: [
    Shadow(color: Colors.cyan.withValues(alpha: 0), blurRadius: 0),
  ],
)

// Highlighted style: the same shadow fades in with its color
TextStyle(
  fontSize: 56,
  color: Colors.cyan,
  shadows: [
    Shadow(color: Colors.cyan.withValues(alpha: 0.6), blurRadius: 24),
  ],
)

Watch Out: inherit Values Must Match

A TextStyle has inherit set to true by default, while ready-made styles coming from the theme are usually defined with inherit: false. If you mix the two and there is an interpolatable field that neither style defines, TextStyle.lerp throws in debug mode, because the result would be a jumpy transition. The safest approach is to derive both styles from the same source with copyWith:

final base = Theme.of(context).textTheme.titleLarge!;

final normalStyle = base.copyWith(color: Colors.grey);
final selectedStyle = base.copyWith(
  color: Colors.cyan,
  fontSize: 32,
  fontWeight: FontWeight.bold,
);

A Real Example: Animated Tab Labels

Making the selected label grow and stand out in category tabs is one of the most common use cases for AnimatedDefaultTextStyle:

class CategoryTabs extends StatefulWidget {
  const CategoryTabs({super.key, required this.categories});

  final List<String> categories;

  @override
  State<CategoryTabs> createState() => _CategoryTabsState();
}

class _CategoryTabsState extends State<CategoryTabs> {
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        for (var i = 0; i < widget.categories.length; i++)
          Padding(
            padding: const EdgeInsets.only(right: 16),
            child: GestureDetector(
              onTap: () => setState(() => _selectedIndex = i),
              child: AnimatedDefaultTextStyle(
                duration: const Duration(milliseconds: 250),
                curve: Curves.easeOut,
                style: TextStyle(
                  fontSize: i == _selectedIndex ? 22 : 16,
                  fontWeight:
                      i == _selectedIndex ? FontWeight.bold : FontWeight.w500,
                  color: i == _selectedIndex ? Colors.white : Colors.white54,
                ),
                child: Text(widget.categories[i]),
              ),
            ),
          ),
      ],
    );
  }
}

Each tab has its own AnimatedDefaultTextStyle. When the selection changes, the old tab shrinks and fades while the new one grows and stands out. Both animations are triggered at the same time by a single setState.

A Note on Performance

Animating properties that affect the size of the text, such as fontSize, letterSpacing or fontWeight, causes the text to be re-measured (laid out) on every frame of the animation. For a single title this is not a problem. But if you are enlarging many texts at once in a long list, it is cheaper to animate the color with AnimatedDefaultTextStyle and the growth with AnimatedScale. AnimatedScale does not trigger layout; it only scales the painting.

Which One When?

• Only the text style changes: AnimatedDefaultTextStyle. • The box, border or background around the text changes too: AnimatedContainer for the box, AnimatedDefaultTextStyle for the text. • The text itself changes (e.g. a counter value): AnimatedSwitcher. • You need full control (repeat, reverse, chained steps): DefaultTextStyleTransition with an AnimationController.

Conclusion

AnimatedDefaultTextStyle adds noticeable life to your UI with just a few lines of change. It is ideal for tabs, selected list items, focused form labels and highlighted headings. Things to keep in mind: derive both styles from the same source, remember that non-interpolatable properties switch halfway through, and consider the layout cost of animations that change size.