Flutter module 切换 Release 状态

554 阅读1分钟

前言

项目目前通过 cocoapods 集成 flutter module。 由于 flutter 在 debug 和 release 状态下的性能不同,有时需要在本地调试时查看 release 状态的表现,通过 xcode buildconfigration 切换需要重新编译整个项目,耗时较长。想找出可快速切换成 release 的方法。

思路

flutter_application_path = '../my_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'MyApp' do
  install_all_flutter_pods(flutter_application_path)
end

post_install do |installer|
  flutter_post_install(installer) if defined?(flutter_post_install)
end

通过 Podfile 可以看出是通过 podhelper.rb 脚本将 flutter 相关代码集成到主工程的,那么查看其源码实现应该可以找到方法。

阅读源码

podhelper.rb

def install_flutter_application_pod(flutter_application_path)
  
  ...
  
  # Compile App.framework and move it and Flutter.framework to "BUILT_PRODUCTS_DIR"
  script_phase name: 'Run Flutter Build test Script',
    script: "set -e\nset -u\nsource \"#{flutter_export_environment_path}\"\nexport VERBOSE_SCRIPT_LOGGING=1 && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/xcode_backend.sh build",
    execution_position: :before_compile

  # Embed App.framework AND Flutter.framework.
  script_phase name: 'Embed Flutter Build test Script',
    script: "set -e\nset -u\nsource \"#{flutter_export_environment_path}\"\nexport VERBOSE_SCRIPT_LOGGING=1 && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/xcode_backend.sh embed_and_thin",
    execution_position: :after_compile
end

以上是 podhelper.rbinstall_flutter_application_pod 方法主要内容,该方法生成了 Xcode Build Phase 中的两段 Script Phase

image.png

image.png

可以看到是执行了 flutter sdk 目录下的 xcode_backend.sh 脚本

xcode_backend.sh


PROG_NAME="$(follow_links "${BASH_SOURCE[0]}")"
BIN_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
FLUTTER_ROOT="$BIN_DIR/../../.."
DART="$FLUTTER_ROOT/bin/dart"

"$DART" "$BIN_DIR/xcode_backend.dart" "$@"

可以看到执行了 xcode_backend.dart

xcode_backend.dart

String parseFlutterBuildMode() {
    // Use FLUTTER_BUILD_MODE if it's set, otherwise use the Xcode build configuration name
    // This means that if someone wants to use an Xcode build config other than Debug/Profile/Release,
    // they _must_ set FLUTTER_BUILD_MODE so we know what type of artifact to build.
    final String? buildMode = (environment['FLUTTER_BUILD_MODE'] ?? environment['CONFIGURATION'])?.toLowerCase();

    if (buildMode != null) {
      if (buildMode.contains('release')) {
        return 'release';
      }
      if (buildMode.contains('profile')) {
        return 'profile';
      }
      if (buildMode.contains('debug')) {
        return 'debug';
      }
    }
}

可以看到是通过环境变量 FLUTTER_BUILD_MODE 来区分的

结论

那么在刚才生成的 Script Phase 设置下这个环境变量就可以了

export FLUTTER_BUILD_MODE=release

image.png