[Solved] Flutter: Change font family in ThemeData with .copyWith

Question

Asked by Josip D on January 10, 2022 (source).

I know that you can define a new ThemeData object with your own font like this:

ThemeData(fontFamily: 'Roboto')

However, I want to copy an existing ThemeData by using the copyWith method:

ThemeData.dark().copyWith(...)

Sadly, there is no argument fontFamiliy in copyWith. I only want to change the fontFamily and not define an entirely new TextTheme.

How do I copy an existing ThemeData and change its font familiy?

Answer

Question answered by M14 (source).

Try something like this:

ThemeData darkTheme = ThemeData.dark().copyWith(
    textTheme: ThemeData.dark().textTheme.apply(
          fontFamily: 'Roboto',
        ),
    primaryTextTheme: ThemeData.dark().textTheme.apply(
          fontFamily: 'Roboto',
        ),
    accentTextTheme: ThemeData.dark().textTheme.apply(
          fontFamily: 'Roboto',
        ),
); 

If you look at the sources, it's the same thing:

enter image description here

This is about the same thing: https://github.com/flutter/flutter/issues/41276

I don't know why exactly you needed to copy font, but sometimes it makes sense to set fontFamily in theme MaterialApp. About this there is in: Changing the font family in Flutter when using ThemeData.dark() or ThemeData.light()

DART FLUTTER MOBILE
SHARE: