Flutter 可以很方便的使用自定义字体,不仅能够将其用于整个应用里,还可以用在某个单独的 widget 中。使用自定义字体具体步骤:
- 导入字体文件
- 在 pubspec.yaml 中声明字体
- 设置默认字体
- 将字体用于特定 widget
1. 导入字体文件
要使用字体,你需要将字体文件导入到项目中。常见的做法是将字体文件放在项目根目录下的 fonts 或者 assets 文件夹中。
例如,如果你想要在项目中导入 Raleway 和 Roboto Mono 字体,文件夹结构会像下面这样:
awesome_app/ fonts/
Raleway-Regular.ttf
Raleway-Italic.ttf
RobotoMono-Regular.ttf
RobotoMono-Bold.ttf
2. 在 pubspec.yaml 中声明字体
你已经有一个字体可以使用,接下来则需要告诉 Flutter 它在哪。你可以在 pubspec.yaml 中像下面这样声明:
flutter:
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Italic.ttf
style: italic
- family: RobotoMono
fonts:
- asset: fonts/RobotoMono-Regular.ttf
- asset: fonts/RobotoMono-Bold.ttf
weight: 700
2.1 pubspec.yaml 选项的定义
名称 | 作用 |
---|---|
family | 属性决定了字体的名称,你将会在 TextStyle 的 fontFamily 属性中用到。 |
asset | 是字体文件对于 pubspec.yaml 文件的相对路径。这些文件包含了字体中字形的轮廓。构建应用时,这些文件将会被包含在应用程序的资源包中。 |
weight | 属性指定了文件中字体轮廓的字重为 100 的整数倍,并且范围在 100 和 900 之间。这些值对应 FontWeight 并能够在 TextStyle 对象的 FontWeight 属性上使用。 |
style | 属性指定文件中字体的轮廓是否为 italic 或 normal。这些值对应 FontStyle 并能够在 TextStyle 对象的 fontStyle属性上使用。 |
3. 设置默认字体
如何应用这些字体? 你有两种选择:1\将其设为默认字体,或者仅在某些特定 Widget 中使用。
如果你想要设为默认字体,请将 fontFamily 设为应用(全局)theme 的属性的一部分。提供的 fontFamily 的值必须与 pubspec.yaml 中声明的名称相匹配。
MaterialApp(
title: 'Custom Fonts',
// Set Raleway as the default app font.
theme: ThemeData(fontFamily: 'Raleway'),
home: MyHomePage(),
);
4. 将字体用于特定 Widget
如果你希望在特定 Widget(例如 Text Widget)中使用该字体,可以通过 TextStyle 中进行指定。
在这个例子中,我们将在一个 Text Widget 上使用 RobotoMono 字体。同样的,这里的 fontFamily 的值必须与 pubspec.yaml 中声明的值相匹配。
Text(
'Roboto Mono sample',
style: TextStyle(fontFamily: 'RobotoMono'),
);
4.1 字体样式
如若TextStyle指定的字体样式缺少相应的字体文件,Engine 则会使用一个更加通用的字体文件,并尝试推断所请求的字体 weight 和样式的轮廓。
完整样例
字体
Raleway 和 RobotoMono 字体从Google Fonts下载。
pubspec.yaml设置
name: custom_fonts
description: An example of how to use custom fonts with Flutter
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Italic.ttf
style: italic
- family: RobotoMono
fonts:
- asset: fonts/RobotoMono-Regular.ttf
- asset: fonts/RobotoMono-Bold.ttf
weight: 700
uses-material-design: true
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Custom Fonts',
// Set Raleway as the default app font.
theme: ThemeData(fontFamily: 'Raleway'),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
// The AppBar uses the app-default Raleway font.
appBar: AppBar(title: Text('Custom Fonts')),
body: Center(
// This Text widget uses the RobotoMono font.
child: Text(
'Roboto Mono sample',
style: TextStyle(fontFamily: 'RobotoMono'),
),
),
);
}
}