如何用 Style Dictionary 把 less 变量转为 Flutter ThemeData?
解读
面试官真正想考察的是“设计令牌(Design Token)跨平台落地”的完整链路,而非简单地把 .less 文件复制到 Dart 里。国内一线团队(阿里、腾讯、字节、美团)普遍把 Less 变量作为“视觉基线”,再通过 Style Dictionary 生成多端代码,以保证 Flutter、小程序、H5 的样式同源。回答时要突出三点:
- Less 变量必须先用“规范格式”写,才能被 Style Dictionary 识别;
- 通过自定义转换(transform)与格式化(format)把令牌变成 Dart 代码;
- 最终产物要直接塞进
ThemeData,并保留“主题切换”与“暗色模式”的扩展能力。
如果候选人只回答“跑个官方 CLI 就行”,会被认为缺乏工程化落地经验;必须给出.less → tokens.json → 自定义 transform → .dart → ThemeData的完整闭环,并说明如何在 CI 里校验令牌一致性。
知识点
- Design Token 三层语义:
- Global Token(raw value,如
#ff5722) - Alias Token(语义化,如
@color-primary) - Component Token(业务层,如
@button-primary-bg)
- Global Token(raw value,如
- Style Dictionary 的“属性过滤器”与“文件路径匹配”机制,用于把 Less 变量映射到正确的令牌层级。
- Less 变量语法与 Style Dictionary 的“兼容写法”——必须写成
@key: value;并在编译前用 PostCSS 插件抽成 JSON,否则 Style Dictionary 无法直接解析.less。 - Transform 生命周期:
attribute/cti → name/kebab → color/hex8flutter → size/flutterDp,需要自定义color/hex8flutter把 ARGB 转成Color(0xFF…)形式。 - Format 生命周期:官方只提供
dart/class.dart模板,需自写flutter/theme_data.dart模板,把 Map 展开成ThemeData(...)构造函数,同时输出extension CustomColorScheme on ColorScheme以便业务层调用。 - 主题切换:生成的 Dart 文件要包含
lightTokens、darkTokens两个常量,并在MaterialApp层通过ValueNotifier<ThemeData>动态切换。 - 国内合规:生成的 Dart 文件头部必须加
// GENERATED CODE - DO NOT MODIFY BY HAND以及公司版权头,防止被误改;CI 里用style-dictionary lint校验令牌是否被删除或改名。 - 性能优化:令牌数量过万时,需开启
outputReferences: true,让 Dart 侧保留引用关系,减少重复const Color()实例,降低包体积约 12%。
答案
-
规范 Less 变量
在packages/theme/src/less/global.less中按“三层令牌”写法:// Global @color-red-50: #ffebee; // Alias @color-primary: @color-red-50; // Component @button-primary-bg: @color-primary;用
postcss-less-extract插件在build:tokens脚本里把变量抽成tokens/global.json:{ "color": { "red": { "50": { "value": "#ffebee" } }, "primary": { "value": "{color.red.50.value}" } }, "button": { "primary": { "bg": { "value": "{color.primary.value}" } } } } -
配置 Style Dictionary
新建sd.config.js:const flutterColorTransform = { name: 'color/hex8flutter', type: 'value', matcher: token => token.attributes.category === 'color', transformer(token) { const hex = token.value.replace('#', ''); return `0xFF${hex}`; } }; const flutterFormat = { name: 'flutter/theme_data', formatter(dictionary) { const light = {}; const dark = {}; dictionary.allTokens.forEach(t => { const path = t.path.join('_'); if (t.attributes.theme === 'dark') { dark[path] = t.value; } else { light[path] = t.value; } }); return `
// GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart';
const Map<String, dynamic> lightTokens = {JSON.stringify(dark, null, 2)};
extension TokenColor on ColorScheme { Color get primary => Color(lightTokens['color_primary'] as int); }
ThemeData buildThemeData(Brightness brightness) { final tokens = brightness == Brightness.dark ? darkTokens : lightTokens; return ThemeData( colorScheme: ColorScheme.light( primary: Color(tokens['color_primary'] as int), ), ); }`; } };
module.exports = { source: ['tokens/**/*.json'], platforms: { flutter: { transforms: ['attribute/cti', 'name/kebab', flutterColorTransform], buildPath: 'lib/gen/', files: [{ destination: 'theme_data.g.dart', format: 'flutter/theme_data' }] } } };
3. 运行与集成
```bash
npm install -g style-dictionary
style-dictionary build --config sd.config.js
产物 lib/gen/theme_data.g.dart 直接 git 提交,并在 main.dart 中使用:
ValueNotifier<ThemeData> theme = ValueNotifier(buildThemeData(Brightness.light));
MaterialApp(
theme: theme.value,
darkTheme: buildThemeData(Brightness.dark),
home: MyHomePage(),
);
- CI 校验
在.github/workflows/design-token.yml中加一步:
若设计师删改令牌导致 Dart 文件变化,CI 会失败,强制走 MR 评审。- run: npm ci - run: npm run build:tokens - run: git diff --exit-code lib/gen/theme_data.g.dart
拓展思考
- 如果业务线要“动态下发”主题包,可把 Style Dictionary 产物上传到 CDN,Flutter 侧用
rootBundle.loadString拉取 JSON,再通过computeisolate 解析成ThemeData,实现“服务端换肤”。 - 当令牌里出现渐变或阴影等复合值时,需扩展
color/hex8flutter为gradient/flutter转换器,把 JSON 中的linear-gradient(...)转成Gradient.linear对象,并在模板里生成static const Gradient primaryGradient。 - 对于“品牌色算法”场景(阿里 Ant Design 的“色彩生成算法”),可在 Style Dictionary 之前加一步 Node 脚本,根据主色自动计算 10 个梯度色,再写入令牌,保证 Flutter、H5、小程序三端梯度完全一致。