面试题答案
一键面试实现思路
- 创建统一的样式类:定义一个类来管理统一的文本样式,包含字体大小、颜色和字体族的属性。
- 使用Theme:利用Flutter的Theme系统,将定义好的文本样式应用到整个应用的文本组件上,这样可以保证在iOS和Android平台上表现一致。
关键代码
- 定义统一样式类
class AppTextStyle {
static const double fontSize = 16.0;
static const Color textColor = Colors.black;
static const String fontFamily = 'Roboto';
}
- 应用到Theme
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
bodyText1: TextStyle(
fontSize: AppTextStyle.fontSize,
color: AppTextStyle.textColor,
fontFamily: AppTextStyle.fontFamily,
),
),
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('统一文本样式'),
),
body: Center(
child: Text(
'这是一段示例文本',
style: Theme.of(context).textTheme.bodyText1,
),
),
);
}
}
在上述代码中,首先定义了AppTextStyle
类来统一管理文本样式属性。然后在MyApp
的ThemeData
中,通过textTheme
设置bodyText1
的样式,在HomePage
的Text
组件中,使用Theme.of(context).textTheme.bodyText1
应用统一的文本样式。