2 ways to add fonts in flutter App
Fonts are a set of typefaces or styles of text characters that are used to display written content. In the context of mobile apps, fonts play a crucial role in determining how text is presented to users. They influence the visual appearance and readability of text elements within the app, such as headings, body text, buttons, labels, and other user interface elements.
Fonts in mobile apps can affect the overall design, aesthetics, and user experience of the application. Different fonts convey different emotions and tones, so app developers and designers carefully select fonts that align with the app’s branding, target audience, and purpose.
In this tutorial we will learn the two methods to add fonts in flutter application.
First method: Add font files in to the project.
Second method: Use google_fonts package.
Let’s see how to add font using first method.
Method 1: import font files in project
Step 1: Import font files
To work with custom fonts in flutter, we have to import the font files in our project. First create a fonts directory in root directory of our project. Then import fonts in it.
Step 2: Declare fonts in pubspec file
After you’ve imported fonts in project, you need to inform Flutter about its location. This can be achieved by adding a font description within the pubspec.yaml file.
flutter:
fonts:
- family: Roboto
fonts:
- asset: fonts/Roboto-Bold.ttf
- asset: fonts/Roboto-Italic.ttf
Now run the command ‘flutter pub get’
That’s it. We have done. Now we can use these fonts in our text widgets, Like this.
Text(
'This is roboto font',
style: TextStyle(fontFamily: 'Roboto'),
),
Set default font in Flutter app
We can also set default font in our flutter app like this
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'Roboto'
),
home: const HomeScreen(),
);
Method 2 : Use google_fonts package
The “google_fonts” package is a popular package in the Flutter ecosystem that allows developers to easily use Google Fonts in their Flutter applications. Google Fonts is a collection of free, open-source fonts that can be used in various projects, including websites and mobile apps.
By adding this dependency to our Flutter project, we gain access to a wide variety of fonts provided by Google Fonts. We can then use these fonts in our app’s text elements, ensuring a consistent and visually appealing typography.
Step 1: Add package name in pubspec.yaml
Add package ‘google_fonts: ^5.1.0’ in pubspec.yaml under dependencies section, and run command ‘flutter pub get’.
Now we can use google fonts in our app’s Text elements like this
Text(
'This is roboto font',
style: GoogleFonts.roboto())
We can also change overall text style like this
Text(
'This is roboto font',
style: GoogleFonts.roboto(
textStyle: TextStyle(fontSize: 18, color: Colors.blueAccent)),
)