跳至主要內容

從套件匯出字體

您可以將字體宣告為獨立套件的一部分,而不是將字體宣告為應用程式的一部分。這是跨多個不同專案共用相同字體,或讓程式設計人員將其套件發佈到 pub.dev 的便捷方式。此秘訣使用下列步驟

  1. 將字型加入套件。
  2. 將套件和字型加入應用程式。
  3. 使用字型。

1. 將字體新增至套件

#

要從套件匯出字型,您需要將字型檔案匯入套件專案的 lib 資料夾。您可以將字型檔案直接放在 lib 資料夾中,或放在子目錄中,例如 lib/fonts

在此範例中,假設您有一個名為 awesome_package 的 Flutter 程式庫,其字型位於 lib/fonts 資料夾中。

awesome_package/
  lib/
    awesome_package.dart
    fonts/
      Raleway-Regular.ttf
      Raleway-Italic.ttf

2. 將套件和字體新增至應用程式

#

現在,您可以透過更新應用程式根目錄中的 pubspec.yaml 來使用套件中的字型。

將套件新增至應用程式

#

要將 awesome_package 套件新增為依賴項,請執行 flutter pub add

flutter pub add awesome_package

宣告字體資源

#

現在您已匯入套件,請告知 Flutter 從 awesome_package 尋找字型的位置。

要宣告套件字型,請在字型路徑前加上 packages/awesome_package。這會告知 Flutter 在套件的 lib 資料夾中尋找字型。

yaml
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 來變更文字的外觀。若要使用套件字型,請宣告您想要使用的字型以及字型所屬的套件。

dart
child: Text(
  'Using the Raleway font from the awesome_package',
  style: TextStyle(
    fontFamily: 'Raleway',
  ),
),

完整範例

#

字體

#

Raleway 和 RobotoMono 字型是從 Google Fonts 下載的。

pubspec.yaml

#
yaml
name: package_fonts
description: An example of how to use package fonts with Flutter

dependencies:
  awesome_package:
  flutter:
    sdk: flutter

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

#
dart
import 'package:flutter/material.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',
          ),
        ),
      ),
    );
  }
}

Package Fonts Demo