How to animate the fontSize of a Text in Flutter?

Viewed 3225

Is there any way to animate the increase/decrease of the fontSize in a Text widget?

2 Answers

Probably an easier solution would be to use AnimatedTextStyle.

double _size = 10;
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () => setState(() => _size += 50),
    ),
    body: AnimatedDefaultTextStyle(
      duration: Duration(milliseconds: 400),
      style: TextStyle(fontSize: _size),
      child: Text('A'),
    ),
  );
}

This can be done in many different ways, like using AnimationController, setting up the listener and then calling setState on it. But I think a better way would be to use TweenAnimationBuilder for your use case. Here's the minimal code:

double _size = 10;
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () => setState(() => _size += 30),
    ),
    body: TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 300),
      tween: Tween<double>(begin: _size, end: _size),
      builder: (_, size, __) => Text('A', style: TextStyle(fontSize: size)),
    ),
  );
}
Related