使用 ThemeData.dark() 或 ThemeData.light() 时更改 Flutter 中的字体系列

Sur*_*gch 7 themes dart flutter

我正在尝试设置我的字体MaterialApp。由于我使用的是深色主题,我想只使用copyWith然后更改fontFamily. 但是,copyWith没有更改fontFamily.

MaterialApp(
  theme: ThemeData.dark().copyWith(
    fontFamily: 'MyFontFamily',
  ),
Run Code Online (Sandbox Code Playgroud)

未定义命名参数“fontFamily”。

如何保留深色主题并更改字体系列?(同样的问题ThemeData.light()。)

我找到了解决方案并在下面发布。

Sur*_*gch 25

如果您查看and的源代码,您会发现它所做的只是设置值:ThemeData.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);
Run Code Online (Sandbox Code Playgroud)

这意味着要解决您的问题,您无需担心ThemeData.light()or ThemeData.dark()。只需创建一个新的ThemeData并设置brightness自己除了fontFamily

MaterialApp(
  theme: ThemeData(
    brightness: Brightness.dark,
    fontFamily: 'MyFontFamily',
  ),
Run Code Online (Sandbox Code Playgroud)


yac*_*ers 5

ThemeData.light()使用 flutter 3 及以上版本,使用主题和全局更改 fontFamily 变得更加容易ThemeData.dark(),您需要做的就是通过 进行TextTheme设置TypographyTypography().black用于浅色主题和Typography().white深色主题。对于您的深色主题

MaterialApp(
  theme: ThemeData.dark().copyWith(
    textTheme: Typography().white.apply(fontFamily: 'MyFontFamily'),
  ),
Run Code Online (Sandbox Code Playgroud)

适合浅色主题使用Typography().black

MaterialApp(
  theme: ThemeData.light().copyWith(
    textTheme: Typography().black.apply(fontFamily: 'MyFontFamily'),
  ),
Run Code Online (Sandbox Code Playgroud)