面试题答案
一键面试- 使用自定义字体
- 方法:将所需字体文件添加到项目中,然后在Flutter应用中引用。这样可以完全控制字体显示,不受平台默认字体的影响。
- 代码实现:
- 首先,在
pubspec.yaml
文件中声明字体:
- 首先,在
flutter:
fonts:
- family: MyCustomFont
fonts:
- asset: fonts/MyCustomFont.ttf
- 然后在需要使用该字体的地方,例如在`Text`组件中使用:
Text(
'Hello, Flutter!',
style: TextStyle(fontFamily: 'MyCustomFont'),
);
- 使用
GoogleFonts
- 方法:
GoogleFonts
库提供了大量免费字体,可以方便地在Flutter应用中使用,并且能保证在不同平台上有相似的显示效果。 - 代码实现:
- 先添加依赖到
pubspec.yaml
:
- 先添加依赖到
- 方法:
dependencies:
google_fonts: ^[latest_version]
- 在代码中使用,例如:
import 'package:google_fonts/google_fonts.dart';
Text(
'Hello, Google Fonts!',
style: GoogleFonts.lato(),
);
- 设置全局字体
- 方法:通过
ThemeData
来设置应用的全局字体,这样所有使用默认样式的文本组件都会使用统一的字体。 - 代码实现:
- 在
MaterialApp
中设置theme
:
- 在
- 方法:通过
MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
bodyText1: TextStyle(fontFamily: 'MyCustomFont'),
),
),
home: MyHomePage(),
);
这样在应用内使用Text
组件且不指定style
时,会默认使用MyCustomFont
字体。