面试题答案
一键面试- 在主题中配置Text相关属性:
- 在Flutter中,通过
ThemeData
来配置应用的主题。对于Text
的样式,可以在ThemeData
的textTheme
属性中进行设置。textTheme
是TextTheme
类型,它包含了不同级别的文本样式,如displayLarge
、headlineMedium
、bodySmall
等。 - 例如,要设置默认的字体大小、颜色和字体样式:
ThemeData theme = ThemeData( textTheme: TextTheme( bodyMedium: TextStyle( fontSize: 16.0, color: Colors.black, fontStyle: FontStyle.normal, ), ), );
- 这里设置了
bodyMedium
级别的文本样式,字体大小为16.0,颜色为黑色,字体样式为正常。你还可以对其他如displayLarge
等不同级别的文本样式进行类似设置。
- 在Flutter中,通过
- 在Text Widget中应用配置:
- 当在主题中配置好
TextTheme
后,在Text
组件中可以直接使用。如果没有在Text
组件中显式设置样式,它会自动使用主题中对应的TextTheme
样式。 - 例如:
Scaffold( body: Center( child: Text('This is a sample text'), ), );
- 上述
Text
组件会使用主题中textTheme
里bodyMedium
(如果没有特别指定,Text
默认使用bodyMedium
样式)的样式设置,即字体大小16.0,颜色黑色,字体样式正常。如果想使用其他级别的样式,可以在Text
组件中指定:
Scaffold( body: Center( child: Text( 'This is a sample text', style: Theme.of(context).textTheme.displayLarge, ), ), );
- 这里通过
Theme.of(context).textTheme.displayLarge
获取主题中displayLarge
级别的文本样式并应用到Text
组件上。
- 当在主题中配置好