在Flutter中使用ThemeData.dark()或ThemeData.light()时如何更改字体族?

7
我试图设置我的MaterialApp的字体。由于我正在使用深色主题,我想只使用copyWith方法,然后更改fontFamily。但是,copyWith没有更改fontFamily的选项。
MaterialApp(
  theme: ThemeData.dark().copyWith(
    fontFamily: 'MyFontFamily',
  ),

命名参数 'fontFamily' 未定义。

我如何保持暗主题并更改字体系列?(ThemeData.light() 也有同样的问题。)

我找到了一个解决方案,下面会发布。

3个回答

25
如果您查看source codeThemeData.light()ThemeData.dark(),您会发现它们所做的就是设置brightness值。
/// 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);

这意味着要解决您的问题,您不需要费心处理 ThemeData.light()ThemeData.dark()。只需创建一个新的 ThemeData 并在 fontFamily 之外自己设置 brightness 即可:
MaterialApp(
  theme: ThemeData(
    brightness: Brightness.dark,
    fontFamily: 'MyFontFamily',
  ),

3

使用Flutter 3及以上版本,通过主题ThemeData.light()ThemeData.dark()全局更改字体族系变得更加容易,你只需通过Typography设置TextTheme即可。在浅色主题中使用Typography().black,在暗色主题中使用Typography().white

在您的情况下(针对暗色主题):
MaterialApp(
  theme: ThemeData.dark().copyWith(
    textTheme: Typography().white.apply(fontFamily: 'MyFontFamily'),
  ),

对于浅色主题,请使用Typography().black
MaterialApp(
  theme: ThemeData.light().copyWith(
    textTheme: Typography().black.apply(fontFamily: 'MyFontFamily'),
  ),

1

既然你只是在设置brightness,我认为更容易的方法是使用DefaultTextStyle

DefaultTextStyle(
  style: TextStyle(
    fontFamily: 'YourFontFamily',
  ),
  child: YourWidget(),
)

有趣。所以你会用这个来包装整个小部件树? - Suragch
是的,除了在 MaterialApp 中设置外,最好在那里使用 Theme。对于其他情况,应该使用 DefaultTextStyle。没有必要使用 Theme 小部件(只是为了更改 TextStyle)。 - iDecode
相关链接:https://www.youtube.com/watch?v=DUX1uVCewvk - Suragch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接