Changing the font family in Flutter when using ThemeData.dark() or ThemeData.light()
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(),
)
Comments
-
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 usecopyWith
and then change thefontFamily
. However,copyWith
doesn't have an option to change thefontFamily
.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 over 2 yearsInteresting. So you'd wrap the whole widget tree with this?
-
iDecode over 2 yearsYes, except for setting it in the
MaterialApp
, it's better to useTheme
there. For elsewhere,DefaultTextStyle
should be the way to go. There is no need to use aTheme
widget (just for changing theTextStyle
). -
Ali Abbas over 2 yearsYou saved my time.
-
Suragch over 2 yearsRelated: youtube.com/watch?v=DUX1uVCewvk