Adding Custom Fonts in Flutter Using google_fonts and GetX: A Step-by-Step Guide

Flutter Google Fonts Tutorial with GetX | Dynamic Font Selection with Full Code


The google_fonts package allows you to use a wide variety of fonts from Google Fonts in your Flutter application. In this tutorial, we’ll integrate google_fonts with GetX for easy state management, creating a responsive and flexible app layout.


Prerequisites

  1. Flutter SDK: Ensure you have Flutter installed.
  2. GetX Package: We’ll use the get package for state management.
  3. google_fonts Package: Add this to your pubspec.yaml file.
 dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  google_fonts: ^3.0.1

Run flutter pub get to install the dependencies.


Step 1: Setting up the Controller

We’ll create a FontController to manage the font style selections using GetX.

font_controller.dart

 import 'package:get/get.dart';
 import 'package:google_fonts/google_fonts.dart';
 import 'package:flutter/material.dart';

 class FontController extends GetxController {
  // Set default font to Roboto
  var currentFont = GoogleFonts.roboto().fontFamily.obs;

  void changeFont(String fontName) {
    currentFont.value = GoogleFonts.getFont(fontName).fontFamily;
   }
 }

In this controller:

  • currentFont: Tracks the selected font.
  • changeFont: Changes the font style based on the provided font name.

Step 2: Setting up the View

The view will contain a dropdown menu to select a font and apply it to a text widget in real-time.

font_view.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'font_controller.dart';

 class FontView extends GetView {
  final List fonts = ['Roboto', 'Lobster', 'Oswald', 'Pacifico', 'Montserrat'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Fonts Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(() {
              return Text(
                "Flutter Google Fonts with GetX",
                style: TextStyle(fontFamily: controller.currentFont.value, fontSize: 24),
              );
            }),
            const SizedBox(height: 20),
            DropdownButton(
              value: controller.currentFont.value,
              onChanged: (String? newFont) {
                if (newFont != null) {
                  controller.changeFont(newFont);
                }
              },
              items: fonts.map>((String font) {
                return DropdownMenuItem(
                  value: GoogleFonts.getFont(font).fontFamily,
                  child: Text(font),
                );
              }).toList(),
              hint: const Text('Select a Font'),
             ),
           ],
         ),
       ),
     );
   }
 }

In this view:

  • Obx Widget: Displays text with the current font selected in currentFont.
  • DropdownButton: Lists font options, allowing users to change the font in real time.

Step 3: Setting up the Binding

To inject FontController into the view, we’ll create a binding.

font_binding.dart

 import 'package:get/get.dart';
 import 'font_controller.dart';

 class FontBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => FontController());
   }
 }

This ensures the FontController is initialized only when needed, optimizing resources.


Step 4: Running the App

Finally, update main.dart to configure the binding and routing.

main.dart

 import 'package:flutter/material.dart';
 import 'package:get/get.dart';
 import 'font_view.dart';
 import 'font_binding.dart';

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

 class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(
          name: '/',
          page: () => FontView(),
          binding: FontBinding(),
        ),
      ],
      title: 'Google Fonts Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
       ),
     );
   }
 }

Wrapping Up

In this guide, we covered:

  1. Using google_fonts to style text dynamically.
  2. GetX for state management to bind a custom font controller.
  3. Organized MVC structure with bindings, ensuring efficient and modular code.

Now, you have a complete example of using google_fonts with GetX in Flutter to change and apply different fonts to text widgets.