Flutter利用Dart的getter实现字体样式的简化书写

在使用 Flutter 开发 App 时,如果设计出了一套字体的规范,页面中所有的字体都会按照规范来绘制的,我们可以利用 Dart 的 getter 来实现字体样式的简写。

例如下面时我一个 App 的字体设计规范:

字体无非就是包括了:大小、粗细、颜色三个纬度,可以做一个简单的封装来实现字体的简写,下面是我封装的一个字体简写方式:

import 'package:calorie_scan/utils/layout.dart';
import 'package:flutter/material.dart';

// 基础字体样式
final TextStyle textRegular = TextStyle(
  fontSize: px2dp(14),
  fontFamily: "Outfit",
  fontWeight: FontWeight.w400,
);

// 中等粗细
final TextStyle textMedium = textRegular.copyWith(
  fontWeight: FontWeight.w500,
);

// 粗体
final TextStyle textBold = textRegular.copyWith(
  fontWeight: FontWeight.w600,
);

// 给 TextStyle 添加扩展
extension TextStyleExtension on TextStyle {
  TextStyle get regular => textRegular;
  TextStyle get medium => textMedium;
  TextStyle get semiBold => textBold;
  // 不同的尺寸
  // 38,30,26,24,22,18,17,16,14,12,11,10
  TextStyle get size38 => copyWith(fontSize: px2dp(38), height: 48 / 38);
  TextStyle get size30 => copyWith(fontSize: px2dp(30), height: 38 / 30);
  TextStyle get size26 => copyWith(fontSize: px2dp(26), height: 33 / 26);
  TextStyle get size24 => copyWith(fontSize: px2dp(24), height: 30 / 24);
  TextStyle get size22 => copyWith(fontSize: px2dp(22), height: 28 / 22);
  TextStyle get size18 => copyWith(fontSize: px2dp(18), height: 23 / 18);
  TextStyle get size17 => copyWith(fontSize: px2dp(17), height: 21 / 17);
  TextStyle get size16 => copyWith(fontSize: px2dp(16), height: 20 / 16);
  TextStyle get size14 => copyWith(fontSize: px2dp(14), height: 18 / 14);
  TextStyle get size12 => copyWith(fontSize: px2dp(12), height: 15 / 12);
  TextStyle get size11 => copyWith(fontSize: px2dp(11), height: 14 / 11);
  TextStyle get size10 => copyWith(fontSize: px2dp(10), height: 13 / 10);

  // 颜色
  // #101812 #767976 #AAB2AA #FFFFFF
  TextStyle get primary => copyWith(color: const Color(0xFF101812));
  TextStyle get secondary => copyWith(color: const Color(0xFF767976));
  TextStyle get tertiary => copyWith(color: const Color(0xFFAAB2AA));
  TextStyle get button => copyWith(color: const Color(0xFFFFFFFF));
  // 链接颜色
  TextStyle get link => copyWith(color: const Color(0xFF50BA28));
  // ... 更多颜色
}

主要的原理就是给 TextStyle 添加扩展,并且利用了 TextStyle 的 copyWith 方法实现字体样式的自定义,通过上面定义,在页面中调用的时候就可以如下调用了:

// 12 号字体,链接颜色;后面的 link和size12的顺序是可以随便调整的;
textMedium.size12.link
// 黑体16加上自定义颜色;如果颜色也是在设计规范,完全可以在将颜色也写到扩展里面
textBold.size16.copyWith(color: Colors.red);

上面的链式调用是部分先后顺序的,这样在开发的时候就可以减少很多的样板代码了,并且调整的时候只需要修改扩展里面的代码即可。

留下回复