under
under

Reputation: 3067

How to troubleshoot default font in Flutter

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. I was confused about the dark and light themes

Upvotes: 0

Views: 897

Answers (2)

under
under

Reputation: 3067

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:

  1. Add font(s) to your pubspec.yaml
    fonts:
        - family: my font family
          fonts:
            - asset: fonts/myfontfile.ttf

  1. 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, 
),

Upvotes: 0

Gwhyyy
Gwhyyy

Reputation: 9166

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.

Upvotes: 1

Related Questions