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

Flutter文本对齐问题:点击按钮后底部文本与按钮位置互换如何修复?

问题修复:点击按钮后文本与按钮位置互换的问题

问题原因

你的代码中,录制状态下显示的Lottie动画未设置固定尺寸,导致Stack的高度随动画内容动态变化。而外层Column使用了mainAxisAlignment: MainAxisAlignment.center进行居中布局,当Stack高度改变时,整个Column的子元素会重新计算居中位置,最终造成文本与按钮的相对位置看起来发生了互换。

解决方案

给包含Lottie的Stack设置固定宽高,确保无论是否显示动画,Stack的尺寸都保持一致,这样Column的布局就不会因状态变化而偏移。同时给Lottie设置适配规则,让动画在固定容器内正常显示。

修改后的代码

return Scaffold(
  body: Consumer2<ThemeNotifier, RecorderNotifier>(
    builder: (context, theme, recorder, child) => Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const SizedBox(height: 32.0),
        Center(
          // 固定Stack的容器尺寸
          child: SizedBox(
            width: MediaQuery.of(context).size.width * 0.35,
            height: MediaQuery.of(context).size.width * 0.35,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Visibility(
                  visible: recorder.isRecording,
                  child: Lottie.asset(
                    'assets/recording_animation.json',
                    fit: BoxFit.contain, // 让动画适配容器尺寸
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: mRed,
                    border: recorder.isRecording ? null : Border.all(),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    color: mWhiteColor,
                    iconSize: MediaQuery.of(context).size.width * 0.3,
                    icon: Icon(
                      recorder.isRecording
                          ? Icons.stop_rounded
                          : Icons.keyboard_voice_outlined,
                    ),
                    onPressed: () => recorder.isRecording
                        ? RecorderService().stopRecord(recorder)
                        : RecorderService().startRecord(recorder),
                  ),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 32.0),
        const Text(
          'Example',
          style: TextStyle(fontSize: 32.0),
        ),
        const SizedBox(height: 32.0),
      ],
    ),
  ),
);

说明

  • 通过SizedBox固定Stack的宽高(比按钮图标稍大,预留动画显示空间),避免状态切换时布局尺寸波动。
  • 给Lottie添加fit: BoxFit.contain,确保动画在固定容器内自适应显示,不会超出容器边界或撑大布局。
  • 这样无论是否处于录制状态,按钮区域的尺寸都保持稳定,Column的居中布局不会偏移,文本与按钮的上下排列顺序就能稳定保持。

内容的提问来源于stack exchange,提问作者Semih Yilmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:02:07