环境
- Flutter:1.22.4
- Dart:2.10.4
- Fair:0.2.0
https://docs.flutter.dev/development/tools/sdk/releases?tab=macos
集成
添加依赖配置
# 添加 Fair 依赖
dependencies:
fair:
path: ../fair/fair/
# 添加编译器依赖
dev_dependencies:
build_runner: ^1.4.0
fair_compiler:
path: ../fair/compiler/
dependency_overrides:
fair_version:
path: ../fair/flutter_version/flutter_1_22_4
给 Widget 添加注解
- @FairPatch() 修饰组件的定义,必须是顶级class,修饰当前页面为一个动态bundle资源。
- @FairWell() 修饰属性参数,命名需要和注解参数一致
调用编译器生成Bundle
flutter pub run build_runner build
[WARNING] fair_compiler:fairc on lib/dynamic_widget.dart:
[Fair] Compile lib/dynamic_widget.dart into bundle...
[INFO] 17.2s elapsed, 2/3 actions completed.
[Fair] New bundle generated => build/fair/lib_dynamic_widget.fair.json
[INFO] Running build completed, took 18.1s
将页面替换为 FairWidget
// 原先flutter
home: MyHomePage(data: {'title': '58 Fair'})
// 通过网络引用
home: FairWidget(
path: 'http://192.168.31.64:8000/lib_dynamic_widget.fair.json',
data: {'content': 'Red Box'},
)
// 通过assets引用
home: FairWidget(
name: '58 Fair',
path: 'assets/bundle/lib_my_home_page.fair.json',
data: {
'fairProps': jsonEncode({'title': '58 Fair'})
}
)
复杂场景
包含状态的组件
- StatefulWidget
- @FairProps
home: FairWidget(
name: '58 Fair',
path: 'assets/bundle/lib_my_home_page.fair.json',
data: {
'fairProps': jsonEncode({'title': '58 Fair'})
})
https://fair.58.com/zh/guide/simple-demo.html
Build中包含逻辑运算
目前,不是所有的Flutter Widget都可以无痛一键转换。Fair默认支持布局类的转换,这要求build中不含有逻辑运算。如果有逻辑,需要手工去封装或者提供代理的绑定对象。
无论是bundle编写还是生成,都不能包含逻辑运算,Fair当前只能处理静态的布局渲染。
Flutter 包含逻辑示例
// 点击超过3次变减号
Icon getButtonIcon() {
if (_counter > 3) {
return Icon(Icons.minimize);
} else {
return Icon(Icons.add);
}
}
Icon getButtonIcon() {
return Sugar.ifEqual(_counter, 3,
trueValue: Icon(Icons.minimize),
falseValue: Icon(Icons.add));
}
https://fair.58.com/zh/guide/layout_sugar.html#ifequal%E6%9D%A1%E4%BB%B6
https://fair.58.com/zh/guide/sample_custom_plugin.html
不足之处
- Flutter 版本限制(受制于Fair)
- 代码污染(插入一堆语法糖)
- 不能无痛一键转换
- 组件状态处理
- build中不能含有逻辑运算
- 自定义拓展 IFairPlugin:fair/sample_custom_plugin.md at main · wuba/fair
暂不支持(已知问题)
参考:
Flutter Fair
Flutter动态化框架Fair的设计与思考 | Flutter Fair
开源|Fair 在 58 同城拍客 App 中的实践