Material3文本元素占空间更大,如何全局设置高度匹配Material2?
Material3 全局统一文本行高匹配Material2方案
可以通过全局配置主题的TextTheme来统一设置所有文本的行高,不用逐个修改Text组件:
1. 直接全局设置行高为1
在ThemeData中为所有文本样式统一指定height: 1,这样所有继承主题样式的Text组件都会自动应用该配置:
ThemeData( useMaterial3: true, textTheme: const TextTheme( displayLarge: TextStyle(height: 1), displayMedium: TextStyle(height: 1), displaySmall: TextStyle(height: 1), headlineLarge: TextStyle(height: 1), headlineMedium: TextStyle(height: 1), headlineSmall: TextStyle(height: 1), titleLarge: TextStyle(height: 1), titleMedium: TextStyle(height: 1), titleSmall: TextStyle(height: 1), bodyLarge: TextStyle(height: 1), bodyMedium: TextStyle(height: 1), bodySmall: TextStyle(height: 1), labelLarge: TextStyle(height: 1), labelMedium: TextStyle(height: 1), labelSmall: TextStyle(height: 1), ), )
2. 基于Material2主题改造(更贴近原始行高)
如果想保留Material2文本样式的其他特性,仅调整行高,可以先获取Material2的默认TextTheme,再批量修改行高属性:
final material2TextTheme = ThemeData(useMaterial3: false).textTheme; final modifiedTextTheme = material2TextTheme.copyWith( displayLarge: material2TextTheme.displayLarge?.copyWith(height: 1), displayMedium: material2TextTheme.displayMedium?.copyWith(height: 1), displaySmall: material2TextTheme.displaySmall?.copyWith(height: 1), headlineLarge: material2TextTheme.headlineLarge?.copyWith(height: 1), headlineMedium: material2TextTheme.headlineMedium?.copyWith(height: 1), headlineSmall: material2TextTheme.headlineSmall?.copyWith(height: 1), titleLarge: material2TextTheme.titleLarge?.copyWith(height: 1), titleMedium: material2TextTheme.titleMedium?.copyWith(height: 1), titleSmall: material2TextTheme.titleSmall?.copyWith(height: 1), bodyLarge: material2TextTheme.bodyLarge?.copyWith(height: 1), bodyMedium: material2TextTheme.bodyMedium?.copyWith(height: 1), bodySmall: material2TextTheme.bodySmall?.copyWith(height: 1), labelLarge: material2TextTheme.labelLarge?.copyWith(height: 1), labelMedium: material2TextTheme.labelMedium?.copyWith(height: 1), labelSmall: material2TextTheme.labelSmall?.copyWith(height: 1), ); return ThemeData( useMaterial3: true, textTheme: modifiedTextTheme, );
注意事项
- 若个别文本需要特殊行高,可在局部覆盖主题样式,比如:
Text('示例文本', style: Theme.of(context).textTheme.bodyLarge?.copyWith(height: 1.2)) - 设置
height:1会让文本行高与字体实际高度完全匹配,和Material2的紧凑布局一致,能直接解决溢出问题
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

