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

Flutter中如何根据文本长度动态设置选中分类的Container宽度

实现动态宽度的分类项下划线

要让下划线Container的宽度完全匹配文本长度,不用第三方包的话,可以通过TextPainter计算文本的实际渲染宽度,再把这个宽度赋值给Container。具体修改如下:

完整代码

class CategoryList extends Stateful Widget {
  @override
  State<CategoryList> createState() => _CategoryListState();
}

class _CategoryListState extends State<CategoryList> {
  List<String> categories = ['HandBag','Jwellery','FootWear','Dresses','Pens','Jeans','Trousers'];
  int selectedIndex = 2;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 30,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: categories.length,
        itemBuilder: (context, index) {
          return buildCategory(index);
        },
      ),
    );
  }

  Widget buildCategory(int index) {
    // 定义统一的文本样式,和Text组件保持一致
    TextStyle textStyle = TextStyle(
      fontSize: 20,
      color: selectedIndex == index ? Colors.blue : Colors.grey,
    );
    // 计算当前文本的实际渲染宽度
    double textWidth = calculateTextWidth(categories[index], textStyle);

    return GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(categories[index], style: textStyle),
            if (selectedIndex == index)
              Container(
                height: 3,
                width: textWidth, // 赋值计算好的文本宽度
                color: Colors.blue,
              ),
          ],
        ),
      ),
    );
  }

  // 计算文本实际宽度的工具方法
  double calculateTextWidth(String text, TextStyle style) {
    final textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
    )..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.width;
  }
}

关键说明

  1. 统一样式避免偏差:把Text组件的样式抽出来单独定义,确保计算宽度时使用的样式和实际渲染的样式完全一致,防止出现宽度不匹配的情况。
  2. TextPainter精准计算:通过TextPainter的layout方法模拟文本渲染,获取其width属性,这就是文本在界面上实际占用的宽度。
  3. 动态绑定宽度:将计算得到的宽度直接赋值给下划线Container的width参数,就能让下划线和文本长度完全对齐,达到原生下划线的效果。

内容的提问来源于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.21 23:06:24