Shubham Soni Product Engineer @ threedots | Google India Scholar 2018 | Technical Author @ LogRocket

How to use custom fonts in Flutter

4 min read 1376

How to Use Custom Fonts in Flutter

Flutter helps us create beautiful mobile applications for multiple platforms with a single codebase. Isn’t that awesome? Yes, it is.

Designers and developers favor using a custom font to give their app a distinct appearance that helps in building brand awareness and a better product altogether.

Roboto and San Fransisco are the default font family for Android and iOS, respectively. You might have a custom-created font from a designer, or you might have downloaded a font from any other resource like Google Fonts. Either way, you will have to download the font file (.ttf ) and import it to your Flutter project.

In this article, you’ll learn how to add custom a font to your project by creating a basic Flutter app that displays texts with different font styles.

Getting started with custom fonts 🎬

Follow these steps to begin with fonts in Flutter:

  1. Downloading the font file
  2. Importing the font files in a project
  3. Adding the font in the pubspec.yaml
  4. Using the font in an app

1. Downloading the font file 📦

Let’s get started by downloading a custom font from Google Fonts. In this example, we’ll use the Montserrat font. You might have gotten a custom font file from a designer or somewhere else. But in this tutorial, we will be downloading the .ttf font file from Google Fonts. Google Fonts is a catalog containing fonts published under licenses that allow you to use them on any website or an app for commercial or personal use.

Follow these steps to download the font file:

  • Step 1: Visit Google Fonts and search for Monserrat in the search bar
  • Step 2: Click on the Monserrat font
  • Step 3: Now click on the Download family to download the font
  • Step 4: Unzip the downloaded file

2. Importing font files in a project 📂

After downloading, we need to add the font files to our Flutter project. Create a folder named fonts in the root of the Flutter project.

You need to structure the folder like this:

my_app/
  lib
  fonts/
    Montserrat-Regular.ttf

Next, move the Montserrat font files or .ttf files into the fonts folder that you just created.

N.B., you will see many fonts files after unzipping but only copy Monserrat-Regular.ttf, Monserrat-Italic.ttf, Monserrat-Bold.ttf for this tutorial. Later you can experiment with as many variants as you want.

3. Adding font files in pubspec 📝

So now after importing the font files into our Flutter project, we need to add them to our pubspec.yaml. By declaring the font in the pubspec.yaml, you tell Flutter to register this font and remember it so that you can use it all over the project.

You need to follow a specific structure while declaring the font in the pubspec.yaml:

Follow the below structure to declare the font:

flutter:
  fonts:
    - family: Montserrat
      fonts:
        - asset: fonts/Montserrat-Regular.ttf
        - asset: fonts/Montserrat-Italic.ttf
          style: italic
        - asset: fonts/Montserrat-Bold.ttf
          weight: 700

Keep these things in mind while declaring fonts in the pubspec 🤓:

  • Indentation is crucial, and always make sure to have proper spaces as required
  • You can add multiple font families in the same manner (you will see that later)
  • The family determines the name of the font and it should be unique for different font families
  • The asset is the path of the font from the root of the project
  • The weight property represents the weight of the font, an integer value from 100 to 900
  • The style property specifies whether the font is normal or italic

Hint: After adding a font in the pubspec.yaml, always restart the app from the cold. 🔥

Up until now you have successfully imported and added the font. In the next step, you will see how to use the font in the project.

4. Using font in an app 🕹️

Now it’s time for the real action. After all those steps, you’re set up to start using the custom font and make a custom-tailored app.



Let’s see how to use the custom font in a Text widget:

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: Text(
              'Almost before we knew it, we had left the ground.',
              style: TextStyle(
                fontFamily: 'Montserrat',
                fontSize: 36.0,
                color: Colors.teal,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Result:

Montserrat Font Flutter App

You need to use TextStyle to add style to a Text widget. TextStyle takes a fontFamily parameter that is the name of the font that you earlier added in the pubspes.yaml (here Montserrat). Other parameters like fontSize, color, and fontWeight declare the size of the font, color of the font, and weight of the font, respectively.

Instead of declaring the font separately in each Text widget, you can also make a font app-level that will be implemented throughout the app.

By declaring the font in the MaterialApp‘s theme property, you can apply the custom font to the entire app.

Here’s how you add do it 😎:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Montserrat',
      ),
      home: const HomePage(),
    );
  }
}

In the above example, we added Montserrat as the default font family for our app. Every Text widget that you’ll add will now be using Montserrat as their font. Configuring fontWeight and fontStyle to bold and italic will use the Montserrat font that you added for italic and bold in pubspec.yaml.

Here’s a complete example of using different variations of the Montserrat font:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Montserrat',
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontStyle: FontStyle.italic,
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Result:

Bold and Italic Montserrat

At times either your designer or you may want to add multiple fonts in your app to make it more vibrant, expressive, and better looking.

To add another font in the pubspec.yaml, just do the following :

    • Download Dancing Script from Google Fonts
    • Unzip and add it to the fonts folder
    • Add the font to the pubspec.yaml:
      • family: DancingScript
        fonts:

        • asset: fonts/DancingScript-Bold.ttf
          weight: 700
    • Use the DancingScript font by adding a new Text widget in the Column

After adding a Text widget that uses DancingScript, here’s how the HomePage widget will look:

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontStyle: FontStyle.italic,
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
            Text(
              "Almost before we knew it, we had left the ground.",
              style: TextStyle(
                fontFamily: 'DancingScript',
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: Colors.teal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Result:

DancingScript Flutter

Conclusion 🌠

In this tutorial, you learned how you can use custom fonts in a Flutter project.

Another way to use fonts from Google Fonts is by using the google_fonts package. The google_font package can fetch the .ttf or font files once via http at runtime, and cache it in the app’s file system instead of storing it in the fonts folder and declaring the font in the pubspec.yaml. I’m excited to see what you all come up with all this learning.

Good luck! Happy Fluttering! 👨‍💻

If you have any questions, feel free to post them 👇.


More great articles from LogRocket:


Any feedback is welcome 😃.

If you enjoyed this article, you can support us by sharing it with your friends.

Get setup with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now
Shubham Soni Product Engineer @ threedots | Google India Scholar 2018 | Technical Author @ LogRocket

Leave a Reply