Flutter中如何实现富文本Text.rich的内容垂直居中对齐?
Flutter 富文本多字号垂直居中实现方案
问题原因
你设置的TextAlign.center仅作用于水平方向的文本对齐,无法控制垂直方向的对齐逻辑。Flutter 中默认TextSpan的不同字号文本会基于文本基线对齐,因此小字号的AB、EF会自动和大字号CD的底部基线对齐,才会出现你遇到的错位问题。
解决方案
使用WidgetSpan替代普通TextSpan包裹小字号文本,同时指定占位符对齐方式为垂直居中即可,修改后的完整代码如下:
import 'package:flutter/material.dart'; class DraftPage extends StatefulWidget { DraftPage({Key? key}) : super(key: key); @override _DraftPageState createState() => _DraftPageState(); } class _DraftPageState extends State<DraftPage> { @override Widget build(BuildContext context) { final bottomTextStyle = const TextStyle( fontSize: 12, fontWeight: FontWeight.w500, color: Colors.red, ); return Scaffold( appBar: AppBar( title: const Text('Test'), ), body: Container( alignment: Alignment.center, width: 300, height: 57, decoration: const BoxDecoration( color: Colors.yellow, ), child: Text.rich( TextSpan( children: [ WidgetSpan( alignment: PlaceholderAlignment.middle, child: Text('AB', style: bottomTextStyle), ), TextSpan( text: 'CD', style: const TextStyle( fontSize: 40, fontWeight: FontWeight.w500, color: Colors.blue, ), ), WidgetSpan( alignment: PlaceholderAlignment.middle, child: Text('EF', style: bottomTextStyle), ), ], ), textAlign: TextAlign.center, ), ), ); } }
效果说明
修改后AB、CD、EF三个文本段会基于整体的垂直中线对齐,即可实现你需要的效果。
内容的提问来源于stack exchange,提问作者无夜之星辰
相关产品推荐
相关产品推荐

