Flutter 如何实现与多行文本并排摆放的自定义Widget
实现你要的悬挂缩进效果有两种常用的可行方案:
方案1:Row组合布局(最简单,适配绝大多数场景)
核心思路是将and及之前的固定文本,和后续文本拆分为左右两个模块布局,后续文本放在自适应宽度的容器内自动换行,自然就会从and的下方开始对齐:
Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 左侧放置and及之前的文本 const Text( 'aaaaaaaa bbbbb ccccc ddddd and ', style: TextStyle(fontSize: 14, color: Colors.black), ), // 右侧放置后续所有文本,自动换行后不会跑到左侧区域 Expanded( child: Text( 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', style: TextStyle(fontSize: 14, color: Colors.black), ), ), ], )
该方案逻辑简单易维护,只要前后文本样式统一,优先选这个方案即可。
方案2:RichText组合(适合前后文本样式不同的场景)
如果前后文本有字体、颜色、大小等样式差异,可以用RichText配合WidgetSpan实现:
RichText( text: TextSpan( children: [ // 前置文本可自定义样式 const TextSpan( text: 'aaaaaaaa bbbbb ccccc ddddd and ', style: TextStyle(fontSize: 14, color: Colors.black, fontWeight: FontWeight.bold), ), WidgetSpan( alignment: PlaceholderAlignment.top, child: ConstrainedBox( // 宽度可根据实际布局调整,也可嵌套LayoutBuilder动态计算 constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width - 150), child: const Text( 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', style: TextStyle(fontSize: 14, color: Colors.black), ), ), ) ], ), )
内容的提问来源于stack exchange,提问作者dontknowhy
相关产品推荐
相关产品推荐

