flutter:在项目是如何设置字体

  1. 操作步骤
    1. pubspec.yaml的weight问题:字体粗细标准
  2. 在Text里面设置行高height

操作步骤

我们从蓝湖知道设计稿件的字体之后,可以去https://fonts.google.com/ 这个网址下载字体

下载后导入 assets/fonts/


编辑 pubspec.yaml

flutter:
  fonts:
    - family: Poppins
      fonts:
        - asset: assets/fonts/Poppins-Light.ttf
          weight: 300
        - asset: assets/fonts/Poppins-Regular.ttf
          weight: 400
        - asset: assets/fonts/Poppins-Medium.ttf
          weight: 500
        - asset: assets/fonts/Poppins-Bold.ttf
          weight: 700

编写 TextStyle

Text(
  "Online Market",
  style: TextStyle(
    fontSize: 19,
    fontFamily: 'Poppins', // 在pubspec.yaml配置了
    fontWeight: FontWeight.bold,
    color: Colors.white,
    height: 22 / 19,
  ),
),
Text(
  "10",
  style: TextStyle(
    fontSize: 19, 
    fontFamily: 'Poppins',// 在pubspec.yaml配置了
    fontWeight: FontWeight.bold,
    color: Colors.white,
    height: 22 / 19,
  ),
),

使用SizedBox设置间距

Stack(...),
const SizedBox(height: 24),
Text(...);
const SizedBox(height: 27),
Text(...),

pubspec.yamlweight问题:字体粗细标准

这里的 weight 并不是随便写的数字,它对应的是 字体粗细的规范值

Flutter 的 FontWeight 和 weight 数字有一一对应的规则

文件名常见后缀 对应 weight 数字 Flutter 枚举值 说明
Thin 100 FontWeight.w100 极细
ExtraLight / UltraLight 200 FontWeight.w200 特细
Light 300 FontWeight.w300 细体
Regular / Normal / Book 400 FontWeight.w400 常规(默认)
Medium 500 FontWeight.w500 中等
SemiBold / DemiBold 600 FontWeight.w600 半粗
Bold 700 FontWeight.w700 粗体
ExtraBold / UltraBold 800 FontWeight.w800 特粗
Black / Heavy 900 FontWeight.w900 超粗 / 黑体

由于一个字体(比如 Poppins)可能有多个不同的字重文件:

  • Poppins-Light.ttf
  • Poppins-Regular.ttf
  • Poppins-Medium.ttf
  • Poppins-Bold.ttf

Flutter 需要知道 哪个字体文件对应哪个 weight,这样当你写

Text(
  "Hello",
  style: TextStyle(
    fontFamily: 'Poppins',
    fontWeight: FontWeight.w700, // 对应 Bold
  ),
)

Flutter 才能去加载 Poppins-Bold.ttf

上面的代码,我写的是FontWeight.bold,其实就是对应的FontWeight.w700

class FontWeight {
  const FontWeight._(this.index, this.value);

  /// The encoded integer value of this font weight.
  final int index;

  /// The thickness value of this font weight.
  final int value;

  /// Thin, the least thick.
  static const FontWeight w100 = FontWeight._(0, 100);

...............

  /// Black, the most thick.
  static const FontWeight w900 = FontWeight._(8, 900);

  /// The default font weight.
  static const FontWeight normal = w400;

  /// A commonly used font weight that is heavier than normal.
  static const FontWeight bold = w700;

在Text里面设置行高height

如果设计稿标注的「文字大小 19px,行高 22px」,那么在 Flutter 里就要写:

fontSize: 19,
height: 22 / 19, // ≈1.1579

因为height 不是直接的行高,而是 倍数系数,所以必须用设计稿的行高除以字体大小。不同平台(iOS/Android)渲染会有细微差别,但这样设置能保证最大程度贴合设计稿。

×

喜欢就点赞,疼爱就打赏