MST

星途 面试题库

面试题:Flutter 中如何在代码层面统一 iOS 和 Android 字体的基础样式

在Flutter项目里,假设需要统一iOS和Android平台上文本的字体大小、颜色以及字体族,描述一下实现的思路和关键代码。
21.6万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建统一的样式类:定义一个类来管理统一的文本样式,包含字体大小、颜色和字体族的属性。
  2. 使用Theme:利用Flutter的Theme系统,将定义好的文本样式应用到整个应用的文本组件上,这样可以保证在iOS和Android平台上表现一致。

关键代码

  1. 定义统一样式类
class AppTextStyle {
  static const double fontSize = 16.0;
  static const Color textColor = Colors.black;
  static const String fontFamily = 'Roboto';
}
  1. 应用到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类来统一管理文本样式属性。然后在MyAppThemeData中,通过textTheme设置bodyText1的样式,在HomePageText组件中,使用Theme.of(context).textTheme.bodyText1应用统一的文本样式。