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

Viewed 2564

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.

2 Answers

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',
  ),

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(),
)
Related