flutter使用Text的fontFeatures属性实现数字等宽

1,990 阅读1分钟

flutter中数字的宽度并不是一样的,这样会造成组件对齐等问题,如下图所示。

截屏2022-01-28 14.55.29.png

这里为大家介绍使用Text的fontFeatures属性解决该问题。

fontFeatures源码注释A list of [FontFeature]s that affect how the font selects glyphs. (一个影响字体如何选择字形的列表)

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. (对于同时具有比例(可变宽度)和表格图形的字体,这将启用表格图形。表格图形是等宽的(所有相同的宽度),因此它们在图形表格中对齐。)

所以我们在TextStyle的fontFeatures中设置FontFeature.tabularFigures()就可以实现数字的等宽,效果如下图所示。

TextStyle(fontFeatures: [FontFeature.tabularFigures()])

截屏2022-01-28 15.38.22.png