google_fonts

注意:此包处于 Beta 版。API 可能会更改。

Flutter 的 google_fonts 包允许您在 Flutter 应用中轻松使用 fonts.google.com 上的 977 种字体(及其变体)。

入门

google_fonts

使用 google_fonts 包,.ttf.otf 文件无需存储在您的 assets 文件夹中并在
pubspec 中映射。相反,它们可以在运行时通过 http 获取一次,并缓存在应用的​​文件系统中。这对于开发非常理想,并且可以成为希望减小应用包大小的生产应用的​​首选行为。
尽管如此,您仍然可以随时选择将字体文件包含在 assets 中,并且 Google Fonts 包会优先使用预打包的文件而不是通过 http 获取。
因此,Google Fonts 包允许开发人员在不使用相同 API 的情况下,选择预打包字体和通过 http 加载字体。

例如,假设您想在 Flutter 应用中使用 Google Fonts 中的 Lato 字体。

首先,将 google_fonts 包添加到您的 pubspec 依赖项

导入 GoogleFonts

import 'package:google_fonts/google_fonts.dart';

使用默认 TextStyle 使用 GoogleFonts

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(),
),

使用现有的 TextStyle 使用 GoogleFonts

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(
    textStyle: TextStyle(color: Colors.blue, letterSpacing: .5),
  ),
),

或者

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(textStyle: Theme.of(context).textTheme.display1),
),

覆盖 fontSizefontWeightfontStyle

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(
    textStyle: Theme.of(context).textTheme.display1,
    fontSize: 48,
    fontWeight: FontWeight.w700,
    fontStyle: FontStyle.italic,
  ),
),

您还可以使用 GoogleFonts.latoTextTheme() 来创建或修改整个文本主题以使用“Lato”字体。

MaterialApp(
  theme: ThemeData(
    textTheme: GoogleFonts.latoTextTheme(
      Theme.of(context).textTheme,
    ),
  ),
);

或者,如果您想要一个 TextTheme,其中一些样式应使用不同的字体

final textTheme = Theme.of(context).textTheme;

MaterialApp(
  theme: ThemeData(
    textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith(
      body1: GoogleFonts.oswald(textStyle: textTheme.body1),
    ),
  ),
);

将字体文件打包到您的应用程序的 assets 中

google_fonts 包将自动使用您 pubspec.yaml 中的匹配字体文件
assets(而不是在运行时通过 HTTP 获取它们)。一旦您确定了字体
您想使用

  1. https://fonts.google.com 下载字体文件。
    对于任何给定的字体系列,您只需要下载您正在使用的字重和样式。
    斜体样式将在文件名中包含 Italic。字重映射到文件名的如下:
{
  FontWeight.w100: 'Thin',
  FontWeight.w200: 'ExtraLight',
  FontWeight.w300: 'Light',
  FontWeight.w400: 'Regular',
  FontWeight.w500: 'Medium',
  FontWeight.w600: 'SemiBold',
  FontWeight.w700: 'Bold',
  FontWeight.w800: 'ExtraBold',
  FontWeight.w900: 'Black',
}
  1. 将这些字体移动到一个顶级应用目录(例如 google_fonts)。

google_fonts_folder

  1. 确保您已将该文件夹(例如 google_fonts/)在 pubspec.yamlassets 下列出。

google_fonts_pubspec_assets

注意:由于这些文件被列为 assets,因此无需在 pubspec.yamlfonts 部分列出它们。
可以这样做,因为文件是从 Google Fonts API 持续命名的
(所以请务必不要重命名它们!)

GitHub

https://github.com/material-foundation/google-fonts-flutter