Changing the font family in Flutter when using ThemeData.dark() or ThemeData.light()

1,536

Solution 1

If you look at the source code for ThemeData.light() and ThemeData.dark(), you can see that all it does is set the brightness value:

/// A default light blue theme.
///
/// This theme does not contain text geometry. Instead, it is expected that
/// this theme is localized using text geometry using [ThemeData.localize].
factory ThemeData.light() => ThemeData(brightness: Brightness.light);

/// A default dark theme with a teal secondary [ColorScheme] color.
///
/// This theme does not contain text geometry. Instead, it is expected that
/// this theme is localized using text geometry using [ThemeData.localize].
factory ThemeData.dark() => ThemeData(brightness: Brightness.dark);

That means to solve your problem you don't need to bother with ThemeData.light() or ThemeData.dark(). Just create a new ThemeData and set the brightness yourself in addition to the fontFamily:

MaterialApp(
  theme: ThemeData(
    brightness: Brightness.dark,
    fontFamily: 'MyFontFamily',
  ),

Solution 2

Since, all you're doing is setting the brightness, I think the easier way would be to just use DefaultTextStyle.

DefaultTextStyle(
  style: TextStyle(
    fontFamily: 'YourFontFamily',
  ),
  child: YourWidget(),
)
Share:
1,536
Suragch
Author by

Suragch

Read my story here: Programming was my god

Updated on December 25, 2022

Comments

  • Suragch
    Suragch over 1 year

    I'm trying to set the font of my MaterialApp. Since I'm using the dark theme, I'd like to just use copyWith and then change the fontFamily. However, copyWith doesn't have an option to change the fontFamily.

    MaterialApp(
      theme: ThemeData.dark().copyWith(
        fontFamily: 'MyFontFamily',
      ),
    

    The named parameter 'fontFamily' isn't defined.

    How do I keep the dark theme but also change the font family? (Same problem with ThemeData.light().)

    I found a solution and am posting below.

  • Suragch
    Suragch over 2 years
    Interesting. So you'd wrap the whole widget tree with this?
  • iDecode
    iDecode over 2 years
    Yes, except for setting it in the MaterialApp, it's better to use Theme there. For elsewhere, DefaultTextStyle should be the way to go. There is no need to use a Theme widget (just for changing the TextStyle).
  • Ali Abbas
    Ali Abbas over 2 years
    You saved my time.
  • Suragch
    Suragch over 2 years