如何在 Flutter 中为文本的字体大小设置动画?
How to animate the fontSize of a Text in Flutter?
有没有办法在 Text
小部件中为 fontSize
的 increase/decrease 设置动画?
这可以通过许多不同的方式完成,例如使用 AnimationController
、设置侦听器然后在其上调用 setState
。但我认为更好的方法是将 TweenAnimationBuilder
用于您的用例。这是最少的代码:
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)),
),
);
}
可能更简单的解决方案是使用 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'),
),
);
}
有没有办法在 Text
小部件中为 fontSize
的 increase/decrease 设置动画?
这可以通过许多不同的方式完成,例如使用 AnimationController
、设置侦听器然后在其上调用 setState
。但我认为更好的方法是将 TweenAnimationBuilder
用于您的用例。这是最少的代码:
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)),
),
);
}
可能更简单的解决方案是使用 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'),
),
);
}