Wednesday, May 20, 2020

How to implement dynamic font type change in Flutter?



In this article, we will learn how we can change the font family dynamically in Flutter using Google Fonts.

Google fonts allow the developer to use and experiment with multiple fonts available on fonts.google.com. Google tried to minimize the work needed with the pre-bundled font and recently announced the google fonts v1.0 official release for Flutter.

With the new google_fonts package now, you don't need to depend on the old skol method of storing .ttf or .otd files in assets and mapping in the pubspec file. You can simply load the font using https at runtime.

This piece of information is useful for you if you are
1. Making an application that requires a dynamic font change
2. Designing a Text editing application and want to switch between different fonts.
3. Photo editing application and want to display text on the Images with different fonts
4. Learning to use GoogleFonts dynamic change.

Let's not waste any time and start with our project. I will use a a stepwise approach to simplify and explain this project.

Step 1:

Add google fonts dependency in pubspec.yaml file of your project. At the time of writing this blog, the latest version available is 1.1.0. 



Step 2 :

Add an import statement for google fonts to your dart file to get access to all the fonts, also clear the code for the demo app because we will make everything from scratch.
The code is posted below with the respective screenshot to help you.

 import 'package:flutter/material.dart';  
 import 'package:google_fonts/google_fonts.dart';  
 void main() {  
  runApp(MyApp());  
 }  
 class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
 }  
 class _MyAppState extends State<MyApp> {  
  @override  
  Widget build(BuildContext context) {  
   return MaterialApp();  
  }  
 }  



Step 3:

Create a string variable to store the font name. By default, I have saved the Lato font name in the variable. You can check all the fonts on fonts.google.com and choose whatever font you want.

 import 'package:google_fonts/google_fonts.dart';  
 void main() {  
  runApp(MyApp());  
 }  
 class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
 }  
 class _MyAppState extends State<MyApp> {  
   String fontFamily='Lato'; //default font  
  @override  
  Widget build(BuildContext context) {  
   return MaterialApp();  
  }  
 }  




Step 4:

In this step, I will design a simple UI consisting of a Text Widget and a Button Widget. I have already worked on the styling part of the text to make it more visible.
 import 'package:flutter/material.dart';  
 import 'package:google_fonts/google_fonts.dart';  
 void main() {  
  runApp(MyApp());  
 }  
 class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
 }  
 class _MyAppState extends State<MyApp> {  
  String fontFamily = 'Lato'; //default font  
  @override  
  Widget build(BuildContext context) {  
   return MaterialApp(  
    home: Scaffold(  
     body: SafeArea(  
      child: Column(  
       mainAxisAlignment: MainAxisAlignment.spaceBetween,  
       crossAxisAlignment: CrossAxisAlignment.stretch,  
       children: <Widget>[  
        Text(  
         'Font of this line will change',  
         style: TextStyle(  
          fontSize: 25,  
         ),  
         textAlign: TextAlign.center,  
        ),  
        RaisedButton(  
         onPressed: () {  
         },  
         child: Text('Change Font'),  
        )  
       ],  
      ),  
     ),  
    ),  
   );  
  }  
 }  


The UI of the application will look like this.




Step 5: 

This step is one of the essential steps in this tutorial. In this step, we will be using the dynamic loading feature of google fonts.
This feature loads font dynamically using https at runtime, now you don't need to store .ttf or .odt files in the assets folder and map them in pubspec file. If you want to switch between multiple fonts or simply a list of fonts then you just have to store the names of the fonts in a list.
To dynamically load font we use
Text(
  'This is Google Fonts',
  style: GoogleFonts.getFont('Lato'),
),
further, if we want to give styling to this, we can use a property named textStyle in the getFont function parameter.
Text(
  'This is Google Fonts',
  xyle: GoogleFonts.getFont('Lato',textStyle:TextStyle(fontSize:25),),
),
 import 'package:flutter/material.dart';  
 import 'package:google_fonts/google_fonts.dart';  
 void main() {  
  runApp(MyApp());  
 }  
 class MyApp extends StatefulWidget {  
  @override  
  _MyAppState createState() => _MyAppState();  
 }  
 class _MyAppState extends State<MyApp> {  
  String fontFamily = 'Lato'; //default font  
  @override  
  Widget build(BuildContext context) {  
   return MaterialApp(  
    home: Scaffold(  
     body: SafeArea(  
      child: Column(  
       mainAxisAlignment: MainAxisAlignment.spaceBetween,  
       crossAxisAlignment: CrossAxisAlignment.stretch,  
       children: <Widget>[  
        Text(  
         'Font of this line will change',  
         style: GoogleFonts.getFont( //Google fonts dynamic load  
          fontFamily,  
          textStyle: TextStyle(  
           fontSize: 25,  
          ),  
         ),  
         textAlign: TextAlign.center,  
        ),  
        RaisedButton(  
         onPressed: () {},  
         child: Text('Change Font'),  
        )  
       ],  
      ),  
     ),  
    ),  
   );  
  }  
 }  










Step 6:

In this step, we will set the onPressed property of the RaisedButton Widget.
We will write a code such that on the press of button the value stored in the fontFamily variable which we had created before it is changed, and the font of the text is modified instantaneously.
This is the final code snippet for the project and the project is completed finally





We have now completed the project, now you can quickly implement this feature in your flutter project :)
For the complete source code you can visit this Github link 

Conclusion

Time to look at what we learned in this article, Google fonts allow the developer to use and experiment with multiple fonts available on fonts.google.com. Google tried to minimize the work needed with the pre-bundled font and recently announced the google fonts v1.0 official release for Flutter. Now we can use the fonts at the runtime using google fonts dependency.

What's your fav font on fonts.google.com? 
Previous Post
First

post written by:

Hi, Navjyot Singh is a coder, content maker and a freelance developer who's pursuing an undergraduate Engineering degree in Computer Science. He started out as a web developer but later picked up the mobile as his favourite platform to develop applications. A Writer by day and coder by night is loathed to discuss himself as the third person but can be persuaded to do so from time to time.

0 comments: