Home » Web Development » Using Custom Fonts in Flutter – Good way and the Bad!

About Ayusch Jain

Ayusch Jain
Ayusch is a Software Engineer currently working in Android Development. He's worked long enough that he's transformed into an Android himself :P. Additionally, he also maintains a community of Android developers called: AndroidVille and writes about Android on his website: https://ayusch.com

Using Custom Fonts in Flutter – Good way and the Bad!

In this flutter tutorial, we’ll take a look at how to use custom fonts in flutter. Font is essential in establishing your brand identity and default fonts do not always serve the purpose.

Flutter has a very elegant way of using custom fonts and it’s very easy to set it up. As for the font files, I’ll be downloading them from fonts.google.com

The three fonts I’ll be using are: 

  • RobotoCondensed
  • Pangolin
  • Sriracha

Adding the fonts to your flutter app

Create a folder in the root of your project (at the level of lib folder) called assets. This folder contains images, fonts for your app.

Then create another folder named fonts and add the font files in that folder. I’m using four variants of RobotoCondensed here.

Add the entry in Pubspec.yaml

To use the fonts, we’ll have to create an entry in pubspec.yaml file as below.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
fonts:
  - family: RobotoCondensed
    fonts:
      - asset: assets/fonts/RobotoCondensed-Regular.ttf
      - asset: assets/fonts/RobotoCondensed-Bold.ttf
        weight: 900
      - asset: assets/fonts/RobotoCondensed-Light.ttf
        weight: 300
      - asset: assets/fonts/RobotoCondensed-Italic.ttf
  - family: Pangolin
    fonts:
      - asset: assets/fonts/Pangolin-Regular.ttf
  - family: Sriracha
    fonts:
      - asset: assets/fonts/Sriracha-Regular.ttf

The font family defines the name of the font. The options such as weight and italic are used to define the outline of the font. When you set the font style as bold or italic in code, it’ll refer to definitions here to select the appropriate font file. Make sure to have the proper indentation here.

Now there are two ways to use custom fonts in flutter. The good way and the bad way. Let’s see what they are.

Using custom fonts in flutter (the bad way!)

I’ll be creating a sample app to demonstrate this. First, add the following code to your main.dart file.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import 'package:flutter/material.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      debugShowCheckedModeBanner: false,
      home: FontsScreen(title: 'Flutter Demo Home Page'),
    );
  }
}
 
class FontsScreen extends StatefulWidget {
  FontsScreen({Key key, this.title}) : super(key: key);
 
  final String title;
 
  @override
  FontsScreenState createState() => FontsScreenState();
}
 
class FontsScreenState extends State<FontsScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
        ),
      ),
      body: Container(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "This is the default font",
            ),
            Text(
              "This text has fontFamily Pangolin",
            ),
            Text(
              "This text has fontFamily Roboto",
            ),
            Text(
              "This text has fontFamily Sriracha",
            ),
          ],
        ),
      ),
    );
  }
}

Here we have three texts, one for each of the 3 custom fonts and one default font.

The style property of Text widget takes a TextStyle object which contains the options to style our text. We’ll use the fontFamily property to define the family of fonts to use as below. 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Text(
  "This is the default font",
  style: TextStyle(fontSize: 22),
),
Text(
  "This text has fontFamily Pangolin",
  style: TextStyle(
    fontFamily: "Pangolin",
    fontSize: 22,
  ),
),
Text(
  "This text has fontFamily Roboto",
  style: TextStyle(
    fontFamily: "RobotoCondensed",
    fontSize: 22,
  ),
),
Text(
  "This text has fontFamily Sriracha",
  style: TextStyle(
    fontFamily: "Sriracha",
    fontSize: 22,
  ),
),

In addition to this, you can add options such as weight, style to make your font bold or italic. Likewise, we add the styles to the other three Text widgets using different families for each.

1
2
3
4
5
TextStyle(
                fontFamily: "RobotoCondensed",
                fontSize: 22,
                fontWeight: FontWeight.bold
              )

But as mentioned in the heading, this is not the most optimal way to do it.

What happens when you have multiple screens and want to use the same font and style at multiple places?

You’ll have to go around changing each one of them manually. And this as we know is not the best way to do things. There’s a better way to use custom fonts in flutter.

Using custom fonts in flutter (the good way!)

The best way to do it is by defining a textTheme for your app. Text there has some predefined properties such as bodyText1, bodyText2, headline1 etc… which we can alter to use our defined styles.

We’ll define the textTheme in the MaterialApp widget. It contains a property named theme which in turn takes a ThemeData object.

01
02
03
04
05
06
07
08
09
10
11
MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          textTheme: ThemeData.light().textTheme.copyWith(
 
              )),
      debugShowCheckedModeBanner: false,
      home: FontsScreen(title: 'Flutter Demo Home Page'),
    );

Here, we’ve copied the theme from an already existing light theme. But we’ll customise it to suite our needs.

We’ll define bodyText1, bodyText2 and headline 1 for different text widgets.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          textTheme: ThemeData.light().textTheme.copyWith(
                bodyText1:
                    TextStyle(fontFamily: "RobotoCondensed", fontSize: 22),
                bodyText2: TextStyle(fontFamily: "Pangolin", fontSize: 22),
                headline1: TextStyle(fontFamily: "Sriracha", fontSize: 22),
              )),
      debugShowCheckedModeBanner: false,
      home: FontsScreen(title: 'Flutter Demo Home Page'),
    );

We’ve allotted each of them a TextStyle object with different font families. Finally they can be used anywhere as below:

1
style: Theme.of(context).textTheme.bodyText1)

Now whenever you want to change a font family you’ll have to do it at a single place rather than going around changing all the texts that use it.

See, I told ya it was easy to use custom fonts in flutter 😛

Here’s the complete main.dart file for your reference:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import 'package:flutter/material.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          textTheme: ThemeData.light().textTheme.copyWith(
                bodyText1:
                    TextStyle(fontFamily: "RobotoCondensed", fontSize: 22),
                bodyText2: TextStyle(fontFamily: "Pangolin", fontSize: 22),
                headline1: TextStyle(fontFamily: "Sriracha", fontSize: 22),
              )),
      debugShowCheckedModeBanner: false,
      home: FontsScreen(title: 'Flutter Demo Home Page'),
    );
  }
}
 
class FontsScreen extends StatefulWidget {
  FontsScreen({Key key, this.title}) : super(key: key);
 
  final String title;
 
  @override
  FontsScreenState createState() => FontsScreenState();
}
 
class FontsScreenState extends State<FontsScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
        ),
      ),
      body: Container(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "This is the default font",
              style: TextStyle(
                fontSize: 22,
              ),
            ),
            Text("This text has fontFamily Pangolin",
                style: Theme.of(context).textTheme.bodyText1),
            Text("This text has fontFamily Roboto",
                style: Theme.of(context).textTheme.bodyText2),
            Text(
              "This text has fontFamily Sriracha",
              style: Theme.of(context).textTheme.headline1,
            ),
          ],
        ),
      ),
    );
  }
}

Published on Java Code Geeks with permission by Ayusch Jain, partner at our JCG program. See the original article here: Using Custom Fonts in Flutter – Good way and the Bad!

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments