GoogleFonts library something we can’t avoid when it comes to finding freely available fonts for our UIs. In this article, I’m going to show you how to use the official GoogleFonts Plugin for Flutter.

What’re the benefits of using the official plugin?

  • You don’t need to store .ttf or .otf fonts files in your assets directory and mapped in the pubspec. Instead, the package will fetch fonts via HTTP at runtime, and cache in the app’s file system. So you can reduce your app bundle size and saves your development time.
  • The plugin will automatically update your font’s to the there latest version.
  • You can test your app UI with different fonts with less effort.
  • You can still pre-bundle your fonts with this package if you wish to do so.

How to import Google fonts plugin to your app?

First we need to import GoogleFonts plugin into our app. We need to follow 3 simple steps to get this done.

1. Add the google_fonts package to your pubspec dependencies.

Open pubspec.yaml file with a text editor. You can find this file in your project’s root folder. Then you need to mention google_fonts dependency under dependencies.

pubspec.yaml

2. Run flutter pub get to update your dependencies.

Open terminal (command prompt) window and navigate to your project’s root directory. Then run the command flutter pub get . This command will download all the required dependencies and google_fonts plugin into your project.

Terminal Window

3. Import the package to your Dart code

import 'package:google_fonts/google_fonts.dart';

Once you imported the plugin into your Flutter code, you can assign your choice of Google Fonts to any text widget or via TextStyles or TextThemes.

How to use GoogleFonts in Your App?

For this example, I’m going to show you how to apply Google’s Roboto font to your TextStyle.

Text(
  'Hello world!',
  style: GoogleFonts.roboto(),
),

Simple isn’t it? So let’s modify this text little bit by adding a text color and enlarge the font size.

Text(
    'Hello World!',
    textDirection: TextDirection.ltr,
    style: GoogleFonts.roboto(
    textStyle: TextStyle(color: Colors.blue, fontSize: 32)
)

GoogleFonts plugin comes with default styling for basic use. So what we did here override those defaults with our own values.

If you looking for advanced usage of this plugin, please refer to the official plugin documentation.

How to package fonts with App bundle?

If you want to package the fonts with your app bundle instead of fetching fonts dynamically via HTTP, you have to follow the following steps.

  1. Download the required .ttf/.otf font files from https://fonts.google.com
  2. Create a directory in your app directory with the name google_fonts.
  3. List the directory in your pubspec.yaml under assets
Package google fonts with App bundle

Share article:

Permalink: