如何在Flutter中定义主题时使用Google字体

19

我是Flutter的新手。

我安装了这个库以便使用Google字体。

现在我需要在主题数据定义中使用它,并尝试像这样做,但不被允许。


ThemeData appTheme() {
  return ThemeData(
    ...
    fontFamily: GoogleFonts.openSans(),
  );
}

我该怎么做?非常感谢。


5
fontFamily需要一个字符串。使用GoogleFonts.openSans().fontFamily - Riwen
非常感谢@Riwen,如果您想将其添加为答案,我可以接受它。 - user3808307
1
将我的评论重新发布为实际答案。谢谢。 - Riwen
5个回答

57

我重新发表我的评论:fontFamily需要一个String类型的参数。使用GoogleFonts.openSans().fontFamily


13
将以下代码粘贴到您的主题文件中,并将其添加到您的 ThemeData(textTheme:textTheme)中。
final TextTheme textTheme = TextTheme(
  headline1: GoogleFonts.roboto(
      fontSize: 97, fontWeight: FontWeight.w300, letterSpacing: -1.5),
  headline2: GoogleFonts.roboto(
      fontSize: 61, fontWeight: FontWeight.w300, letterSpacing: -0.5),
  headline3: GoogleFonts.roboto(fontSize: 48, fontWeight: FontWeight.w400),
  headline4: GoogleFonts.roboto(
      fontSize: 34, fontWeight: FontWeight.w400, letterSpacing: 0.25),
  headline5: GoogleFonts.roboto(fontSize: 24, fontWeight: FontWeight.w400),
  headline6: GoogleFonts.roboto(
      fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: 0.15),
  subtitle1: GoogleFonts.roboto(
      fontSize: 16, fontWeight: FontWeight.w400, letterSpacing: 0.15),
  subtitle2: GoogleFonts.roboto(
      fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 0.1),
  bodyText1: GoogleFonts.roboto(
      fontSize: 16, fontWeight: FontWeight.w400, letterSpacing: 0.5),
  bodyText2: GoogleFonts.roboto(
      fontSize: 14, fontWeight: FontWeight.w400, letterSpacing: 0.25),
  button: GoogleFonts.roboto(
      fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 1.25),
  caption: GoogleFonts.roboto(
      fontSize: 12, fontWeight: FontWeight.w400, letterSpacing: 0.4),
  overline: GoogleFonts.roboto(
      fontSize: 10, fontWeight: FontWeight.w400, letterSpacing: 1.5),
);

这个视频很好地解释了如何在Flutter中使用主题和字体https://youtu.be/stoJpMeS5aY?t=640


视频中展示的代码所在的网站已经上线了吗? - user3808307
可以获取Flutter、Web和Android XML的代码。https://material.io/design/typography/the-type-system.html#type-scale - Luiz Filipe Medeira
谢谢。我不得不把采纳答案给了Riwen,因为它正好回答了我的问题。 - user3808307
如果您正在使用Google字体并想要调整字体大小,这是一种方法。 - Yaojin
不过,没有必要逐个进行此操作,只需使用该方法获取您正在使用的字体的整个TextTheme即可。例如:GoogleFonts.robotoTextTheme()或GoogleFonts.cinzelDecorativeTextTheme()。 - Ramiro G.M.

10
main.dart文件中添加。
 fontFamily: GoogleFonts.poppins().fontFamily,

enter image description here


1
return MaterialApp( theme:ThemeData(textTheme: GoogleFonts.robotoTextTheme()));

首先导入google_fonts包。 - ajaybadole

0

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