Add font family
Presentation (Building the UI)
Summary
This lesson teaches how to globally apply a custom font to a Flutter application using the google_fonts package. Instead of manually downloading font files and configuring pubspec.yaml, the instructor demonstrates how to inject a Google Font directly into the app's ThemeData. This approach is efficient but requires specific configuration to ensure the font's default text colors adapt correctly to the application's dark mode theme.
Key Ideas
google_fontspackage simplifies font integration by fetching them without requiring manualpubspec.yamlasset configuration.- Applying a font directly to an individual
Textwidget via itsstyleproperty is inefficient for app-wide styling. MaterialApp'sthemeproperty allows setting a global font family by modifying thetextTheme.GoogleFonts.<fontName>TextTheme()applies the selected font to all text styles globally within the application.GoogleFontsdefaults to a light theme text color palette, which causes readability issues (black text) in a dark mode application.- Passing the app's current
TextTheme(e.g.,ThemeData.dark().textTheme) into theGoogleFontsmethod ensures the custom font inherits the correct dark mode colors.
Code Snippets
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: kPrimaryColor,
textTheme: GoogleFonts.montserratTextTheme(ThemeData.dark().textTheme),
),
home: const SplashView(),
);
}My Notes
The instructor uses a VS Code extension to quickly add the google_fonts dependency rather than typing it in pubspec.yaml.
Gotcha: The dark mode text color issue is a very common trap when using this package. By default, GoogleFonts.someTextTheme() assumes a light background. Passing ThemeData.dark().textTheme as an argument is a crucial fix to force the package to inherit white text colors.
[Editor's note] Relying purely on network-fetched fonts via google_fonts can cause a visible "font-swap" pop-in on the first app launch if the user has a slow connection. For production apps following Clean Architecture principles, downloading the .ttf files, placing them in an /assets/fonts folder, and explicitly declaring them in pubspec.yaml is more robust, guarantees offline access, and prevents unexpected UI layout shifts.