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

Flutter按钮布局问题:如何实现text1居中、text2居右

解决Flutter按钮中text1居中、text2居右的布局问题

你的核心问题是原代码用MainAxisAlignment.spaceBetween会让text1居左,无法实现居中效果。要达成text1居中、text2居右的布局,只需调整Row的结构,借助Spacer分配空间即可,修改后的完整代码如下:

import 'package:flutter/material.dart';
import 'package:streeti/static/static_colors.dart';

class ButtonWithBlue extends StatelessWidget {
  const ButtonWithBlue({Key? key, required this.text1, required this.text2})
      : super(key: key);

  final String text1;
  final String text2;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ClipRRect(
        borderRadius: const BorderRadius.all(Radius.circular(20)),
        child: Container(
          height: 75,
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white12,
            border: Border.all(
              color: AppColors.BlueColor,
              width: 1.0,
            ),
          ),
          child: RawMaterialButton(
            onPressed: () {},
            splashColor: Colors.blue,
            child: Stack(
              children: [
                Positioned(
                  right: -20,
                  top: -25,
                  height: 120,
                  width: 120,
                  child: Container(
                    decoration: ShapeDecoration(
                      color: AppColors.BlueColor,
                      shape: const CircleBorder(),
                    ),
                  ),
                ),
                // 移除原居中Container,直接用Row控制布局
                Row(
                  children: [
                    // 左侧Spacer占据剩余空间,让text1居中
                    const Spacer(),
                    Text(
                      text1,
                      style: const TextStyle(color: Colors.black, fontSize: 18),
                    ),
                    // 右侧Spacer维持text1居中,给text2留出位置
                    const Spacer(),
                    // 给text2加右侧内边距,避免被蓝色圆形遮挡
                    Padding(
                      padding: const EdgeInsets.only(right: 30),
                      child: Text(
                        text2,
                        style: const TextStyle(color: Colors.black, fontSize: 18),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

关键修改点说明:

  • 移除外层Container(alignment: Alignment.center),让Row直接填充按钮宽度
  • 两个Spacer()平分按钮左右两侧剩余空间,中间的text1自然处于居中位置
  • 给text2添加右侧内边距,避免被右侧蓝色圆形元素遮挡,保证文字可见性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:43:25