求Flutter中配置Duration参数的Transform.scale用法示例
Flutter 300ms 缩放动画实现示例
如果需要为缩放操作配置300毫秒的过渡时长,通常有两种实现方案:
方案1:使用隐式动画AnimatedScale(推荐)
无需手动管理动画控制器,修改状态即可自动触发动画,是大多数场景下的最优选择:
- 核心配置:将
duration参数固定为Duration(milliseconds: 300)即可匹配需求 - 完整可运行示例代码:
import 'package:flutter/material.dart'; void main() => runApp(const ScaleAnimationDemo()); class ScaleAnimationDemo extends StatefulWidget { const ScaleAnimationDemo({super.key}); @override State<ScaleAnimationDemo> createState() => _ScaleAnimationDemoState(); } class _ScaleAnimationDemoState extends State<ScaleAnimationDemo> { double _currentScale = 1.0; void _triggerScale() { setState(() { _currentScale = _currentScale == 1.0 ? 1.5 : 1.0; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text("300ms缩放示例")), body: Center( child: AnimatedScale( scale: _currentScale, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, // 可选配置动画曲线,默认线性 child: GestureDetector( onTap: _triggerScale, child: Container( width: 200, height: 200, color: Colors.blue, child: const Center( child: Text("点击触发缩放", style: TextStyle(color: Colors.white, fontSize: 18)), ), ), ), ), ), ), ); } }
方案2:手动控制动画+Transform.scale
如果需要自定义动画生命周期(如暂停、倒放、重复播放),可以搭配AnimationController实现:
- 核心变量定义:
late AnimationController _controller; late Animation<double> _scaleAnim; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 300), // 配置300ms动画时长 ); _scaleAnim = Tween<double>(begin: 1.0, end: 1.5).animate( CurvedAnimation(parent: _controller, curve: Curves.easeInOut) ); } @override void dispose() { _controller.dispose(); super.dispose(); }
- 布局层使用:
Transform.scale( scale: _scaleAnim.value, child: Container(width: 200, height: 200, color: Colors.blue), )
- 触发动画调用:
_controller.forward(),倒放调用:_controller.reverse()
内容的提问来源于stack exchange,提问作者dontknowhy
相关产品推荐
相关产品推荐

