How to use Google Fonts in Flutter

Share this post

Using Google Fonts in Flutter is very straightforward and it gives you access to nearly 1000 open-sourced font families. Using google_fonts library allows you to fetch Google Fonts at runtime and cache them in your app’s file system, removing the need for storing the fonts in the assets folder and decreasing your app size. There is of course the option to store the fonts locally as well if you prefer not fetching fonts at runtime.

Install Google Fonts library in Flutter

Run the following command:

flutter pub add google_fonts

Or manually add the following to your pubspec.yaml dependencies list (the version might have changed):

google_fonts: ^2.1.0

Import it in your code:

import 'package:google_fonts/google_fonts.dart';

Using Google Fonts in theme

If you want your entire app to use a particular font, you can just add the font that you want as your text theme (In this case we are using Lato font):

MaterialApp(
  theme: ThemeData(
    textTheme: GoogleFonts.latoTextTheme(
      Theme.of(context).textTheme,
    ),
  ),
);

The above code will make sure that all font variations use Lato as well. If you want to override a particular variation like body1, then you can use the following:

final textTheme = Theme.of(context).textTheme;

MaterialApp(
  theme: ThemeData(
    textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith(
      body1: GoogleFonts.oswald(textStyle: textTheme.body1),
    ),
  ),
);

What the above code does is tell Flutter to use Lato for every font variation except for body1. In this case, all body1 texts in our app will use Oswald.

Use Google Fonts in individual Text widgets

Use the Google Fonts in a Text widget we can just assign the font style to our Text widget textStyle:

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(),
),
// or to load font dynamically:
Text(
  'This is Google Fonts',
  style: GoogleFonts.getFont('Lato'),
),

And of course it’s possible to override other Text properties, like you normally would do:

Text(
  'This is Google Fonts',
  style: GoogleFonts.lato(
    textStyle: Theme.of(context).textTheme.headline4,
    fontSize: 48,
    fontWeight: FontWeight.w700,
    fontStyle: FontStyle.italic,
  ),
),

Bundling font files in your app’s assets

If you prefer not to fetch the fonts during runtime (only the first time, after that they will be cached), then you can:

  • Download the fonts that you want (only the weights and styles needed). It’s important not to rename them!!!
  • Add the fonts to a top-level folder (same level as the lib folder) called google_fonts:
  • Add the google_fonts folder name under assets in your pubspec.yaml file:

There is no need to add your fonts to the fonts section of pubspec.yaml, because we keep the name of font files consistent with what they’re called in the Google Fonts library, so it knows where to get them from.