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

Flutter实现等宽响应式标签容器的方法

问题描述

我有一个标签字符串列表,想要让所有标签拥有相同宽度,而非根据文本长度自适应。比如4个标签时各占相同宽度,文本过长时自动调整;不能使用ListView,所有标签需要根据可用宽度适配——比如总宽度为300、2个标签时每个标签宽度为150(包含内边距等)。但当前实现的标签宽度会随文本长度变化,不符合需求,当前代码如下:

class HomeScreen extends StatelessWidget {
   HomeScreen({Key? key}) : super(key: key);

  List<String> titles=['All','Income','Expense','Debt','Others','Liabilities'];


  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: Container(
        height: 100,
        color: Colors.grey,
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,

children: titles.map((e) => Padding(
          padding: const EdgeInsets.symmetric(horizontal: 2.0),
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8,vertical: 4),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
                color: Colors.white,

              ),
              child: Text(e)),
        )).toList(),),
      ),
    ),
    );
  }
}
解决方案

要实现所有标签平分可用宽度的效果,可使用Expanded组件包裹每个标签容器,让它们自动均分Row的可用空间。同时需将水平方向的内边距放在Expanded内部,避免额外空间干扰宽度计算。修改后的代码如下:

class HomeScreen extends StatelessWidget {
  HomeScreen({Key? key}) : super(key: key);

  List<String> titles = ['All', 'Income', 'Expense', 'Debt', 'Others', 'Liabilities'];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Container(
          height: 100,
          color: Colors.grey,
          child: Row(
            children: titles.map((e) => Expanded(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 2.0),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.white,
                  ),
                  child: Text(
                    e,
                    textAlign: TextAlign.center, // 文本过长时居中显示
                    overflow: TextOverflow.ellipsis, // 文本超出时显示省略号,避免布局溢出
                  ),
                ),
              ),
            )).toList(),
          ),
        ),
      ),
    );
  }
}

关键修改说明

  • 用Expanded包裹每个标签的Padding组件,让所有标签自动平分Row的可用宽度
  • 给Text添加textAlign: TextAlign.center,优化文本过长时的视觉呈现
  • 增加overflow: TextOverflow.ellipsis,防止文本超出标签宽度导致布局异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:55:23