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

Flutter中Row内Text组件的TextOverflow.ellipsis失效问题求助

在Flutter Row中无需额外容器实现文本溢出省略号

要实现Row内Text组件直接显示溢出省略号,核心是给Text添加有效的宽度约束,无需额外嵌套SizedBox或Container,用Flutter自带的Expanded或Flexible组件即可解决问题。

原理说明

Row属于弹性布局,默认情况下子组件会根据自身内容尺寸布局。如果Text没有明确的宽度限制,会尝试展示全部文本内容,不会触发TextOverflow.ellipsis。而Expanded/Flexible会告诉Row:该子组件要分配Row内的可用空间,从而给Text提供明确的宽度约束,配合overflow和maxLines属性就能触发省略号效果。

解决方案代码

替换原代码中Row的子组件部分,用Expanded包裹Text(自动分配Row宽度):

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 200,
              height: 60,
              color: Colors.yellow,
              child: Row(children: const [
                // 用Expanded替代SizedBox,自动分配Row宽度
                Expanded(
                  child: Text(
                    'It is a lengthy text you have to reduce the overflow',
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1, // 必须指定行数,否则文本会换行
                  ),
                ),
                Expanded(
                  child: Text(
                    'Yes, will reduce the length by overflow property',
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ),
              ]),
            )
          ],
        ),
      ),
    );
  }
}

进阶调整

  • 如果需要让两个Text的宽度比例不同,给Expanded添加flex属性即可,比如第一个flex:2、第二个flex:1,这样第一个Text会占据Row宽度的2/3,第二个占1/3。
  • 如果不想让Text强制占满空间,而是根据内容自适应但不超出Row范围,可以用Flexible替代Expanded,它默认会让Text尽可能展示内容,但超出时触发省略号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:12:48