环境

  • Flutter:1.22.4
  • Dart:2.10.4
  • Fair:0.2.0

image.png
https://docs.flutter.dev/development/tools/sdk/releases?tab=macos

集成

添加依赖配置

  1. # 添加 Fair 依赖
  2. dependencies:
  3. fair:
  4. path: ../fair/fair/
  5. # 添加编译器依赖
  6. dev_dependencies:
  7. build_runner: ^1.4.0
  8. fair_compiler:
  9. path: ../fair/compiler/
  10. dependency_overrides:
  11. fair_version:
  12. path: ../fair/flutter_version/flutter_1_22_4

给 Widget 添加注解

  • @FairPatch() 修饰组件的定义,必须是顶级class,修饰当前页面为一个动态bundle资源。
  • @FairWell() 修饰属性参数,命名需要和注解参数一致

image.png

调用编译器生成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

image.png

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

  • Sugar 还在实验中
  • Sugar 只支持有限的几个语法

    自定义拓展功能

  • 网络

  • 选择照片
  • 权限

https://fair.58.com/zh/guide/sample_custom_plugin.html

不足之处

  1. Flutter 版本限制(受制于Fair)
  2. 代码污染(插入一堆语法糖)
  3. 不能无痛一键转换