Skip to content

Commit 72a0a40

Browse files
authored
[google_fonts] Decouple GoogleFontsLite for full tree-shaking and add full feature parity (flutter#12830)
In PR flutter#11433 flutter/packages#11433, google_fonts_lite.dart was introduced as an alternative entry point containing only dynamic font resolution methods and the family descriptor map, allowing compilers to tree-shake the static generated font methods. flutter#11433 was a huge PR, and a breaking one, so we did not publish it yet. Currently this package is set to publish_to: none. For these reasons I decided to follow up on a few more bits of polish here instead of belaboring the mega PR and the contributor's effort. _**After this change, I will migrate this package to material_ui and then we will publish one major release with all of these changes to reduce churn on the ecosystem**._ This PR ensures google_fonts_lite.dart is fully decoupled from the main entry point by sharing an internal configuration singleton, ensuring complete compiler tree-shaking of unused generated font code, while adding missing features to google fonts lite for full feature parity with the non-lite version. ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent e8b7dcf commit 72a0a40

14 files changed

Lines changed: 357 additions & 9 deletions

‎packages/google_fonts/CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
## NEXT
22

33
- Updates minimum supported SDK version to Flutter 3.41/Dart 3.11.
4+
- Adds `config`, `pendingFonts`, and `getTextTheme` to `GoogleFontsLite`.
5+
- Decouples internal base library from the main entry point to ensure complete tree-shakability.
6+
- Adds code samples and documentation for `GoogleFontsLite`.
47
- Adds the `GoogleFontsLite` class to allow tree-shaking unused font code.
58
- Added fonts:
69
- `Akt`

‎packages/google_fonts/README.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,32 @@ return MaterialApp(
115115
```
116116

117117
### Lower build size
118-
The `GoogleFontsLite` class is a replacement for the `GoogleFonts` class containing only a map of all fonts and the `getFont` function. Using *only* `GoogleFontsLite` allows the Dart compiler to tree-shake most of the package's code, yielding a significant reduction in build size.
118+
The `GoogleFontsLite` class is an alternative entry point containing only a map of all fonts and dynamic font resolution methods. Using *only* `GoogleFontsLite` allows the Dart compiler to tree-shake all unused font methods, yielding a significant reduction in build size.
119+
120+
To allow the Dart compiler to tree-shake unused fonts, import `package:google_fonts/google_fonts_lite.dart` instead of `package:google_fonts/google_fonts.dart`.
121+
122+
Do not import `package:google_fonts/google_fonts.dart` when optimizing for bundle size, as that imports the generated static font methods.
123+
124+
<?code-excerpt "readme_excerpts.dart (GoogleFontsLite)"?>
125+
```dart
126+
Widget liteExamples(BuildContext context) {
127+
return Column(
128+
children: <Widget>[
129+
// Single text style:
130+
Text('Dynamic font with minimal bundle size', style: GoogleFontsLite.getFont('Lato')),
131+
// Custom text theme:
132+
Theme(
133+
data: ThemeData(textTheme: GoogleFontsLite.getTextTheme('Lato')),
134+
child: const Text('Themed text'),
135+
),
136+
],
137+
);
138+
}
139+
```
140+
119141

120142
### Visual font swapping
121-
To avoid visual font swaps that occur when a font is loading, use [FutureBuilder](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) and [GoogleFonts.pendingFonts()](https://pub.dev/documentation/google_fonts/latest/google_fonts/GoogleFonts/pendingFonts.html).
143+
To avoid visual font swaps that occur when a font is loading, use [FutureBuilder](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) and [GoogleFonts.pendingFonts()](https://pub.dev/documentation/google_fonts/latest/google_fonts/GoogleFonts/pendingFonts.html) (or `GoogleFontsLite.pendingFonts()`).
122144

123145
See the [example app](https://pub.dev/packages/google_fonts/example).
124146

‎packages/google_fonts/example/lib/readme_excerpts.dart‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,19 @@ void main() {
126126
}
127127

128128
// #enddocregion LicenseRegistration
129+
130+
// #docregion GoogleFontsLite
131+
Widget liteExamples(BuildContext context) {
132+
return Column(
133+
children: <Widget>[
134+
// Single text style:
135+
Text('Dynamic font with minimal bundle size', style: GoogleFontsLite.getFont('Lato')),
136+
// Custom text theme:
137+
Theme(
138+
data: ThemeData(textTheme: GoogleFontsLite.getTextTheme('Lato')),
139+
child: const Text('Themed text'),
140+
),
141+
],
142+
);
143+
}
144+
// #enddocregion GoogleFontsLite

‎packages/google_fonts/generator/google_fonts.tmpl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class GoogleFonts {
3434
/// ```dart
3535
/// GoogleFonts.config.allowRuntimeFetching = false;
3636
/// ```
37-
static final GoogleFontsConfig config = GoogleFontsConfig();
37+
static final GoogleFontsConfig config = sharedGoogleFontsConfig;
3838

3939
/// Returns a [Future] which resolves when requested fonts have finished
4040
/// loading and are ready to be rendered on screen.

‎packages/google_fonts/generator/google_fonts_lite.tmpl‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import 'dart:ui' as ui;
99
import 'package:flutter/material.dart';
1010

1111
import 'google_fonts_base.dart';
12+
import 'google_fonts_config.dart';
1213
import 'google_fonts_descriptor.dart';
1314
import 'google_fonts_variant.dart';
1415

@@ -18,6 +19,67 @@ import 'google_fonts_variant.dart';
1819
/// each font, [GoogleFontsLite] provides dynamic font lookup via [getFont]
1920
/// and [fontsMap], allowing unused font methods to be tree-shaken by the compiler.
2021
abstract final class GoogleFontsLite {
22+
/// Configuration for the [GoogleFontsLite] library.
23+
///
24+
/// Use this to define custom behavior of the GoogleFonts library in your app.
25+
/// For example, if you do not want the GoogleFonts library to make any HTTP
26+
/// requests for fonts, add the following snippet to your app's `main` method.
27+
///
28+
/// ```dart
29+
/// GoogleFontsLite.config.allowRuntimeFetching = false;
30+
/// ```
31+
static final GoogleFontsConfig config = sharedGoogleFontsConfig;
32+
33+
/// Returns a [Future] which resolves when requested fonts have finished
34+
/// loading and are ready to be rendered on screen.
35+
///
36+
/// Usage:
37+
/// ```dart
38+
/// GoogleFontsLite.getFont('Lato');
39+
/// GoogleFontsLite.getTextTheme('Pacifico');
40+
/// await GoogleFontsLite.pendingFonts(); // <-- waits until Lato and Pacifico files have loaded.
41+
/// ```
42+
///
43+
/// To keep things tidy, one can also pass in requested fonts as a list
44+
/// to [pendingFonts].
45+
///
46+
/// ```dart
47+
/// await GoogleFontsLite.pendingFonts(<dynamic>[
48+
/// GoogleFontsLite.getFont('Lato'),
49+
/// GoogleFontsLite.getTextTheme('Pacifico'),
50+
/// ]);
51+
/// ```
52+
///
53+
/// To avoid visual font swaps that occur when a font is loading,
54+
/// consider using [FutureBuilder]. Note: This future cannot be created in
55+
/// [build], as described in [FutureBuilder]'s documentation.
56+
///
57+
/// ```dart
58+
/// late Future<List<void>> googleFontsPending;
59+
///
60+
/// @override
61+
/// void initState() {
62+
/// super.initState();
63+
/// googleFontsPending = GoogleFontsLite.pendingFonts(<dynamic>[
64+
/// GoogleFontsLite.getFont('Lato'),
65+
/// ]);
66+
/// }
67+
///
68+
/// @override
69+
/// Widget build(BuildContext context) {
70+
/// return FutureBuilder(
71+
/// future: googleFontsPending,
72+
/// builder: (context, snapshot) {
73+
/// if (snapshot.connectionState != ConnectionState.done) {
74+
/// return const SizedBox();
75+
/// }
76+
/// return Text('Lato text', style: GoogleFontsLite.getFont('Lato'));
77+
/// },
78+
/// );
79+
/// }
80+
/// ```
81+
static Future<List<void>> pendingFonts([List<dynamic>? _]) => Future.wait(pendingFontFutures);
82+
2183
/// Map of all available Google Fonts families to their variant file descriptors.
2284
static final Map<String, Map<GoogleFontsVariant, GoogleFontsFile>> fontsMap = {
2385
{{#fontEntries}}
@@ -86,4 +148,37 @@ abstract final class GoogleFontsLite {
86148
decorationThickness: decorationThickness,
87149
);
88150
}
151+
152+
/// Retrieve a text theme by its font family name.
153+
///
154+
/// Applies the given font family from Google Fonts to the given [textTheme]
155+
/// and returns the resulting [textTheme].
156+
///
157+
/// Note: [fontFamily] is case-sensitive.
158+
///
159+
/// Parameter [fontFamily] must not be `null`. Throws an [ArgumentError] if no
160+
/// font by name [fontFamily] exists.
161+
static TextTheme getTextTheme(String fontFamily, [TextTheme? textTheme]) {
162+
if (!fontsMap.containsKey(fontFamily)) {
163+
throw ArgumentError("No font family by name '$fontFamily' was found.");
164+
}
165+
textTheme ??= ThemeData.light().textTheme;
166+
return TextTheme(
167+
displayLarge: getFont(fontFamily, textStyle: textTheme.displayLarge),
168+
displayMedium: getFont(fontFamily, textStyle: textTheme.displayMedium),
169+
displaySmall: getFont(fontFamily, textStyle: textTheme.displaySmall),
170+
headlineLarge: getFont(fontFamily, textStyle: textTheme.headlineLarge),
171+
headlineMedium: getFont(fontFamily, textStyle: textTheme.headlineMedium),
172+
headlineSmall: getFont(fontFamily, textStyle: textTheme.headlineSmall),
173+
titleLarge: getFont(fontFamily, textStyle: textTheme.titleLarge),
174+
titleMedium: getFont(fontFamily, textStyle: textTheme.titleMedium),
175+
titleSmall: getFont(fontFamily, textStyle: textTheme.titleSmall),
176+
bodyLarge: getFont(fontFamily, textStyle: textTheme.bodyLarge),
177+
bodyMedium: getFont(fontFamily, textStyle: textTheme.bodyMedium),
178+
bodySmall: getFont(fontFamily, textStyle: textTheme.bodySmall),
179+
labelLarge: getFont(fontFamily, textStyle: textTheme.labelLarge),
180+
labelMedium: getFont(fontFamily, textStyle: textTheme.labelMedium),
181+
labelSmall: getFont(fontFamily, textStyle: textTheme.labelSmall),
182+
);
183+
}
89184
}

‎packages/google_fonts/lib/google_fonts.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@
33
// found in the LICENSE file.
44

55
export 'src/google_fonts_all_parts.dart';
6-
export 'src/google_fonts_config.dart';
6+
export 'src/google_fonts_config.dart' show Config, GoogleFontsConfig;
77
export 'src/google_fonts_lite.dart';

‎packages/google_fonts/lib/google_fonts_lite.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5-
export 'src/google_fonts_config.dart';
5+
export 'src/google_fonts_config.dart' show Config, GoogleFontsConfig;
66
export 'src/google_fonts_lite.dart';

‎packages/google_fonts/lib/src/google_fonts_all_parts.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ class GoogleFonts {
5757
/// ```dart
5858
/// GoogleFonts.config.allowRuntimeFetching = false;
5959
/// ```
60-
static final GoogleFontsConfig config = GoogleFontsConfig();
60+
static final GoogleFontsConfig config = sharedGoogleFontsConfig;
6161

6262
/// Returns a [Future] which resolves when requested fonts have finished
6363
/// loading and are ready to be rendered on screen.

‎packages/google_fonts/lib/src/google_fonts_base.dart‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ import 'package:flutter/material.dart';
88
import 'package:flutter/services.dart';
99
import 'package:http/http.dart' as http;
1010

11-
import '../google_fonts.dart';
1211
import 'file_io.dart' // Stubbed implementation by default.
1312
// Concrete implementation if File IO is available.
1413
if (dart.library.io) 'file_io_desktop_and_mobile.dart'
1514
as file_io;
15+
import 'google_fonts_config.dart';
1616
import 'google_fonts_descriptor.dart';
1717
import 'google_fonts_family_with_variant.dart';
1818
import 'google_fonts_variant.dart';
@@ -164,7 +164,7 @@ Future<void> loadFontIfNecessary(GoogleFontsDescriptor descriptor) async {
164164
}
165165

166166
// Attempt to load this font via http, unless disallowed.
167-
if (GoogleFonts.config.allowRuntimeFetching) {
167+
if (sharedGoogleFontsConfig.allowRuntimeFetching) {
168168
byteData = _httpFetchFontAndSaveToDevice(familyWithVariantString, descriptor.file);
169169
if (await byteData != null) {
170170
return await loadFontByteData(familyWithVariantString, byteData);
@@ -250,7 +250,7 @@ Future<ByteData> _httpFetchFontAndSaveToDevice(String fontName, GoogleFontsFile
250250
}
251251

252252
http.Response response;
253-
final http.Client client = GoogleFonts.config.httpClient ?? _httpClient;
253+
final http.Client client = sharedGoogleFontsConfig.httpClient ?? _httpClient;
254254
try {
255255
response = await client.get(uri);
256256
} catch (e) {

‎packages/google_fonts/lib/src/google_fonts_config.dart‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// found in the LICENSE file.
44

55
import 'package:http/http.dart' as http;
6+
import 'package:meta/meta.dart';
67

78
/// A collection of properties used to specify custom behavior of the
89
/// GoogleFonts library.
@@ -22,3 +23,11 @@ class GoogleFontsConfig {
2223
/// Deprecated. Use [GoogleFontsConfig] instead.
2324
@Deprecated('Use GoogleFontsConfig instead')
2425
typedef Config = GoogleFontsConfig;
26+
27+
/// Shared configuration instance for the Google Fonts library.
28+
///
29+
/// This instance is not exported and is not meant for public consumption.
30+
/// Applications should configure Google Fonts using `GoogleFonts.config` or
31+
/// `GoogleFontsLite.config`.
32+
@internal
33+
final GoogleFontsConfig sharedGoogleFontsConfig = GoogleFontsConfig();

0 commit comments

Comments
 (0)