You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何将SizeTransition动画改为从下向上展开?

实现方法

你只需要为SizeTransition组件添加axisAlignment: 1.0属性,即可实现从底部向上展开的反向动画效果,无需修改动画控制、动画曲线的原有逻辑。

SizeTransition的axisAlignment参数用于控制尺寸动画的展开对齐原点,垂直方向下的规则:

  • 值为-1:组件顶部固定,高度向下增长,即你当前实现的从上向下展开效果
  • 值为1.0:组件底部固定,高度向上增长,即你需要的从下向上展开效果
  • 值为0(默认值):组件中心固定,高度向上下两侧同步增长
修改后完整代码
class VariableSizeContainerExample extends StatefulWidget {
    VariableSizeContainerExample();

    @override
    _VariableSizeContainerExampleState createState() => _VariableSizeContainerExampleState();
}

class _VariableSizeContainerExampleState extends State<VariableSizeContainerExample> with TickerProviderStateMixin {
    AnimationController _controller;
    Animation<double> _animation;

    @override
    void initState() {
        super.initState();
        _controller = AnimationController(
            duration: const Duration(seconds: 1),
            vsync: this,
        );
        _animation = CurvedAnimation(
            parent: _controller,
            curve: Curves.fastLinearToSlowEaseIn,
        );
    }

    _toggleContainer() {
        print(_animation.status);
        if (_animation.status != AnimationStatus.completed) {
            _controller.forward();
        } else {
            _controller.animateBack(0, duration: Duration(seconds: 1));
        }
    }

    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                body: SafeArea(
                    child: Column(
                        children: [
                            TextButton(
                                onPressed: () => _toggleContainer(),
                                child: Text("Toggle container visibility"),
                            ),
                            SizeTransition(
                                sizeFactor: _animation,
                                axis: Axis.vertical,
                                // 新增以下参数即可实现反向展开
                                axisAlignment: 1.0,
                                child: Container(
                                    child: Text(
                                        "This can have variable size",
                                        style: TextStyle(fontSize: 40),
                                    ),
                                ),
                            ),
                            Text("This is below the above container"),
                        ],
                    ),
                ),
            ),
        );
    }
}

修改后运行,组件会从初始隐藏状态从下向上逐步展开显示,收起时也会对应从上向下收缩隐藏,和原有动画方向完全相反。

内容的提问来源于stack exchange,提问作者Mohammed Hamdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 01:21:41