Flutter 实现数字等宽

320 阅读1分钟

如下图所示,数字的宽度不同会导致文案不对齐的问题。

Text组件style属性中的fontFeatures属性可以解决该问题。

Text(
  '123456',
  style: TextStyle(
    fontSize: 12,
    fontWeight: FontWeight.w400,
    fontFeatures: [FontFeature.tabularFigures()],
  ),
);

效果如下:

FontFeature.tabularFigures()源码注释

/// For fonts that have both proportional (varying width) and tabular figures,
/// this enables the tabular figures. Tabular figures are monospaced (all the
/// same width), so that they align in tables of figures.

/// 翻译:对于同时具有比例(可变宽度)和表格图形的字体,这将启用表格图形。表格图形是等宽的(所有相同的宽度),因此它们在图形表格中对齐

/// 省略部分注释...

const FontFeature.tabularFigures() : feature = 'tnum', value = 1;