I have a flutter app targeting Android. I want to change the default font for the app but nothing seems to work.
I have added the google_fonts
package.
I have then modified theme
in main.dart
MaterialApp
as follows:
MaterialApp(
theme: ThemeData(
textTheme: GoogleFonts.latoTextTheme(
Theme.of(context).textTheme,
),
),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.dark,
),
This doesn't work. The font does not change.
I can change individual text widget font using the below syntax and that does work:
Text('Some Text',
style: GoogleFonts.robotoMono(),
),
I have also tried downloading a font and adding it to font assets:
fonts:
- family: Noto
fonts:
- asset: fonts/NotoSans-Regular.ttf
Next, I referred to it in main.dart
, but that does not work either:
theme: ThemeData(
fontFamily: 'Noto',
),
Using the below code returns monospace
. Not sure what that is, I thought the default font should be Roboto.
print('font: ${DefaultTextStyle.of(context).style.fontFamily}');
I have tried to run flutter clean
, to uninstall the app, but none of this helps.
How can I go about troubleshooting this?
UPDATE
Found the problem. Seems that the dark theme settings are overriding the font change in theme. I expected them to be separate settings, but obviously that's not the case...
CodePudding user response:
please, make sure you added the:
void main() {
WidgetsFlutterBinding.ensureInitialized(); // add this before runApp
runApp(MyApp());
}
it's necessary for using the font themes from the google_fonts
package in your MaterialApp's theme property.
CodePudding user response:
The problem was my misunderstanding of how light and dark themes work. Anyway, posting here if anyone else made the same mistake.
So to change the default font if you are using dark theme do this:
- Add font(s) to your
pubspec.yaml
fonts:
- family: my font family
fonts:
- asset: fonts/myfontfile.ttf
- Define themes in
main.dart
:
MaterialApp(
theme: ThemeData(
brightness: Brightness.light,
fontFamily: 'my font family'
),
darkTheme: ThemeData(
brightness: Brightness.dark,
fontFamily: 'my font family'
),
themeMode: ThemeMode.system,
),