以 package 的方式使用字体
如何从 package 中导出字体。
自定义字体,除了可以把字体文件作为应用的一部分之外,还可以通过 package 的方式使用,这样有助于跨项目的字体共享,也可以更方便的发布到 pub.dev。
步骤
#将字体添加到 package
将 package 和字体添加到应用
使用字体
1. 将字体添加到 package
#
如果要导出字体,请将文件放置在 package 的 lib 目录或其子目录中。当前示例使用名为 awesome_package 的 Flutter package 中的 lib/fonts 目录。请将该 package 目录放置在应用目录的同一层级。
-
awesome_package/
lib/
- awesome_package.dart
fonts/
- Raleway-Regular.ttf
- Raleway-Italic.ttf
- pubspec.yaml
2. 将 package 和字体添加到应用
#
现在你可以使用该 package 以及它提供的字体。我们来编辑 应用程序 根目录下的 pubspec.yaml 文件。
将 package 添加到应用中
#在应用程序的目录下,使用 package 路径描述符
flutter pub add "awesome_package:{path: ../awesome_package}"
声明字体资源
#
在你应用的 pubspec.yaml 文件中,声明来自 awesome_package 的字体文件。
要想声明 package 中的字体,必须在 packages/awesome_package 的路径前加上字体声明。这将会让 Flutter 检索到 lib package 的文件夹中的字体。
flutter:
fonts:
- family: Raleway
fonts:
- asset: packages/awesome_package/fonts/Raleway-Regular.ttf
- asset: packages/awesome_package/fonts/Raleway-Italic.ttf
style: italic
3. 使用字体
#
你可以使用 TextStyle
来更改文本的外观。在使用 package 中的字体时,你不仅需要声明该文字所要使用的字体,还需要声明字体所属的 package。
child: Text(
'Using the Raleway font from the awesome_package',
style: TextStyle(fontFamily: 'Raleway'),
),
完整样例
#字体
#这里所使用的 Raleway 和 RobotoMono 字体都是从 Google Fonts 下载的。
pubspec.yaml
#
name: package_fonts
description: An example of how to use package fonts with Flutter
environment:
sdk: ^3.13.0
dependencies:
awesome_package:
path: ../awesome_package
flutter:
sdk: flutter
material_ui: ^1.11.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
fonts:
- family: Raleway
fonts:
- asset: packages/awesome_package/fonts/Raleway-Regular.ttf
- asset: packages/awesome_package/fonts/Raleway-Italic.ttf
style: italic
uses-material-design: true
main.dart
#
import 'package:material_ui/material_ui.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(title: 'Package Fonts', home: MyHomePage());
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
// The AppBar uses the app-default font.
appBar: AppBar(title: const Text('Package Fonts')),
body: const Center(
// This Text widget uses the Raleway font.
child: Text(
'Using the Raleway font from the awesome_package',
style: TextStyle(fontFamily: 'Raleway'),
),
),
);
}
}
除非另有说明,本文档之所提及适用于 Flutter 3.50 版本。本页面最后更新时间:2026-11-20。查看文档源码 或者 为本页面内容提出建议。