flutterdart

How to Set Different fonts for different locales in Flutter


Is there any way to set different fonts for different locals? English font is the default for my app, but I need a different font for my Arabic locale.


Solution

  • Use Locale and Theme

    This problem requires two things:

    The locale can easily be retrieved by calling window.locale from dart:ui. There is an quite in-depth stack overflow post on locale here if you need more information on the locale aspects.

    Based upon the locale, we set the fontFamily property on the ThemeData to the desired font defined in our pubspec.yaml file. (instructions on adding a custom font are here)

    Example

    import 'dart:ui';
    import 'package:flutter/material.dart';
    
    class App extends StatefulWidget {
      const App({Key? key}) : super(key: key);
    
      @override
      State<App> createState() => _AppState();
    }
    
    class _AppState extends State<App> {
      void rebuildOnLocaleChange() => setState(() {});
    
      @override
      Widget build(BuildContext context) {
        final platformDispatcher = PlatformDispatcher.instance;
    
        // Retrieve locale from the system information.
        Locale myLocale = platformDispatcher.locale;
        platformDispatcher.onLocaleChanged = rebuildOnLocaleChange;
    
        return MaterialApp(
          theme: ThemeData(
            // If language is english - we use the default font which is a sans-serif roboto font
            // If not, we use the serif roboto font, must be added in asset and pubspec.yaml to work.
            // TODO: replace the languageCode check with what you need.
            fontFamily: myLocale.languageCode == "en" ? null : "RobotoSerif",
          ),
          home: const AppScreen(),
        );
      }
    }
    
    // Just a simple screen with a text updating when the locale changes.
    class AppScreen extends StatelessWidget {
      const AppScreen({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Text(
              "Test",
              style: Theme.of(context).textTheme.displayLarge,
            ),
          ),
        );
      }
    }
    
    main() => runApp(const App());
    

    Pictures below shows the Theme is set with the default font when the languageCode is "en" (left) and the custom font for other locales (right).

    Default font Custom font