Flutter 自訂字型

留言

目錄

  1. 將字型檔放入專案資料夾內
  2. 在 pubspec.yaml 定義字型資訊
  3. 設定預設字型
  4. 在特定 Widget 設定字型
  5. 完整範例程式碼

雖然 Android 和 iOS 內建都有字型,但常有自訂字型的需求,所以這篇會教你如何在 Flutter 使用自訂字型。

將字型檔放入專案資料夾內

此範例是放在 ./assets/fonts 資料夾內:

1
2
3
4
5
6
7
assets/
fonts/
FiraCode-Medium.ttf
mononoki-Bold.ttf
mononoki-BoldItalic.ttf
mononoki-Italic.ttf
mononoki-Regular.ttf

pubspec.yaml 定義字型資訊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
flutter:
fonts:
- family: FiraCode
fonts:
- asset: assets/fonts/FiraCode-Medium.ttf
- family: Mononoki
fonts:
- asset: assets/fonts/mononoki-Regular.ttf
- asset: assets/fonts/mononoki-Bold.ttf
weight: 700
- asset: assets/fonts/mononoki-Italic.ttf
style: italic
- asset: assets/fonts/mononoki-BoldItalic.ttf
weight: 700
style: italic

設定預設字型

1
2
3
4
5
MaterialApp(
title: 'Custom Fonts',
theme: ThemeData(fontFamily: 'FiraCode'),
home: MyHomePage(title: 'Custom Fonts'),
);

在特定 Widget 設定字型

1
2
3
4
5
6
7
8
9
Text(
'Custom Fonts',
style: TextStyle(
fontFamily: 'Mononoki',
fontSize: 30.0,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.italic,
),
)

完整範例程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Custom Fonts',
theme: new ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'FiraCode',
),
home: new MyHomePage(title: 'Custom Fonts'),
);
}
}

class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(this.title),
),
body: Column(
children: <Widget>[
new Text(
'<-- Custom Fonts ->>',
style: TextStyle(fontSize: 30.0),
),
new Text(
'Custom Fonts',
style: TextStyle(
fontFamily: 'Mononoki',
fontSize: 30.0,
),
),
new Text(
'Custom Fonts',
style: TextStyle(
fontFamily: 'Mononoki',
fontSize: 30.0,
fontWeight: FontWeight.w700,
),
),
new Text(
'Custom Fonts',
style: TextStyle(
fontFamily: 'Mononoki',
fontSize: 30.0,
fontStyle: FontStyle.italic,
),
),
new Text(
'Custom Fonts',
style: TextStyle(
fontFamily: 'Mononoki',
fontSize: 30.0,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.italic,
),
),
],
),
);
}
}

詳情可參考 Using custom fonts - Flutter 官方文件

分享:

討論區