【发布时间】:2021-01-21 23:54:26
【问题描述】:
如何更改应用程序的每个文本以使用特定字体?我可以使用TextStyle() 单独更改它们,但是如何使我的应用程序默认为特定字体?你能告诉我怎么做吗?
【问题讨论】:
-
这个链接可以解决你的问题:stackoverflow.com/a/64549111
标签: flutter fonts themes font-family
如何更改应用程序的每个文本以使用特定字体?我可以使用TextStyle() 单独更改它们,但是如何使我的应用程序默认为特定字体?你能告诉我怎么做吗?
【问题讨论】:
标签: flutter fonts themes font-family
Flutter 使用自定义字体,您可以将自定义字体应用于整个应用程序或单个小部件。此配方通过以下步骤创建一个使用自定义字体的应用程序:
1.导入字体文件
要使用字体,请将字体文件导入项目。通常的做法是将字体文件放在 Flutter 项目根目录的 fonts 或 assets 文件夹中。
例如,要将 Raleway 和 Roboto Mono 字体文件导入项目,文件夹结构可能如下所示:
awesome_app/
fonts/
Raleway-Regular.ttf
Raleway-Italic.ttf
RobotoMono-Regular.ttf
RobotoMono-Bold.ttf
2。在 pubspec 中声明字体
一旦你确定了一种字体,告诉 Flutter 在哪里可以找到它。您可以通过在 pubspec.yaml 文件中包含字体定义来做到这一点。
flutter:
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Italic.ttf
style: italic
3.将字体设置为默认字体 对于如何将字体应用于文本,您有两种选择:作为默认字体或仅在特定小部件中。
要将字体用作默认字体,请将fontFamily 属性设置为应用程序theme 的一部分。提供给fontFamily 的值必须与pubspec.yaml 中声明的family 名称匹配。
MaterialApp(
title: 'Custom Fonts',
// Set Raleway as the default app font.
theme: ThemeData(fontFamily: 'Raleway'),
home: MyHomePage(),
);
4.在特定小部件中使用字体
Text(
'Roboto Mono sample',
style: TextStyle(fontFamily: 'RobotoMono'),
);
完整示例 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'),
),
),
);
}
}
【讨论】:
如果您想使用其中一种Google fonts,请使用材料团队的官方google_fonts 包。
dependencies:
google_fonts: ^2.1.0
MaterialApp(
theme: ThemeData(
textTheme: GoogleFonts.latoTextTheme(
Theme.of(context).textTheme,
),
),
);
【讨论】: