雖然flutter提供很多方便的字型可以用在text widget上,但沒有我們想要的字型時還是可以使用別人提供的字型,尤其將字型設成獨立的package非常好用,可以方便地使用在不同專案上,總共有以下3步:
可以將字體文件直接放在 lib 文件夾或子目錄中,例如 lib/fonts。在這個例子中,假設有一個名為 awesome_package 的 Flutter library,其中的字體位於 lib/fonts 文件夾中
awesome_package/
lib/
awesome_package.dart
fonts/
Raleway-Regular.ttf
Raleway-Italic.ttf
現在可以透過更新App根目錄中的 pubspec.yaml 來使用package裡的字體
將package添加到App
dependencies:
awesome_package: <latest_version>
然後要宣告package字體,請在字體路徑前加上 packages/awesome_package。這告訴 Flutter 在package的 lib 文件夾中查找字體
flutter:
fonts:
- family: Raleway
fonts:
- asset: packages/awesome_package/fonts/Raleway-Regular.ttf
- asset: packages/awesome_package/fonts/Raleway-Italic.ttf
style: italic
使用TextStyle
更改text wdget
child: Text(
'Using the Raleway font from the awesome_package',
style: TextStyle(
fontFamily: 'Raleway',
package: 'awesome_package',
),
),
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
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: 'awesome_package',
),
),
),
);
}
}
參考資料:
https://docs.flutter.dev/cookbook/design/package-fonts