FROM THE BOOKSHELF / A PAGE TO KEEP
技术
67 分钟
Flutter CI/CD 与发布流程
胡新宇
发布于 2026-05-22
系统讲解Flutter GitHub Actions/Codemagic CI配置、iOS证书与Android签名、Fastlane自动化及灰度发布策略

Flutter CI/CD 与发布流程 (CI/CD & Release)
模块:模块十 · 架构与工程化
前置知识:Flutter 构建命令、Git 基础、测试基础
Flutter 多环境配置
使用 --dart-define 区分环境
# 三套环境(开发/测试/生产)
# 使用 --dart-define 传递编译时常量(比 .env 文件更安全,不会打入 APK)
# 开发环境
flutter run \
--dart-define=ENV=development \
--dart-define=API_URL=https://dev-api.example.com \
--dart-define=ENABLE_LOGS=true
# 测试环境
flutter run \
--dart-define=ENV=staging \
--dart-define=API_URL=https://staging-api.example.com \
--dart-define=ENABLE_LOGS=true
# 生产环境
flutter build apk \
--dart-define=ENV=production \
--dart-define=API_URL=https://api.example.com \
--dart-define=ENABLE_LOGS=false \
--release
// lib/core/config/app_config.dart
class AppConfig {
// 从编译时常量读取,若未定义使用默认值
static const String env = String.fromEnvironment(
'ENV',
defaultValue: 'development',
);
static const String apiUrl = String.fromEnvironment(
'API_URL',
defaultValue: 'https://dev-api.example.com',
);
static const bool enableLogs = bool.fromEnvironment(
'ENABLE_LOGS',
defaultValue: true,
);
// 便捷 getter
static bool get isProduction => env == 'production';
static bool get isDevelopment => env == 'development';
static bool get isStaging => env == 'staging';
}
Android Flavor(更完整的多环境支持)
// android/app/build.gradle
android {
flavorDimensions "environment"
productFlavors {
development {
dimension "environment"
applicationIdSuffix ".dev" // com.example.app.dev
versionNameSuffix "-dev"
resValue "string", "app_name", "MyApp (Dev)"
}
staging {
dimension "environment"
applicationIdSuffix ".staging" // com.example.app.staging
versionNameSuffix "-staging"
resValue "string", "app_name", "MyApp (Staging)"
}
production {
dimension "environment"
// 不添加后缀:com.example.app
resValue "string", "app_name", "MyApp"
}
}
}
# 构建指定 Flavor
flutter build apk --flavor development --dart-define=ENV=development
flutter build apk --flavor production --dart-define=ENV=production --release
// lib/main_development.dart
void main() {
runApp(const App(config: DevelopmentConfig()));
}
// lib/main_production.dart
void main() {
runApp(const App(config: ProductionConfig()));
}
GitHub Actions 构建流水线
完整的 CI 配置
# .github/workflows/ci.yml
name: Flutter CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
FLUTTER_VERSION: '3.19.0'
jobs:
# ─── Job 1:代码检查 ───────────────────────────
analyze:
name: 代码分析
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 设置 Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
cache: true # 缓存 Flutter SDK
- name: 缓存 pub 依赖
uses: actions/cache@v3
with:
path: ~/.pub-cache
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
- run: flutter pub get
- run: flutter analyze # Dart 静态分析
- run: dart format --check . # 代码格式检查
# ─── Job 2:测试 ───────────────────────────────
test:
name: 运行测试
runs-on: ubuntu-latest
needs: analyze # 依赖代码分析通过
steps:
- uses: actions/checkout@v4
- name: 设置 Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
cache: true
- run: flutter pub get
- name: 运行测试(含覆盖率)
run: flutter test --coverage --reporter=github
- name: 上传覆盖率报告
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: coverage/lcov.info
# ─── Job 3:构建 Android ─────────────────────────
build-android:
name: 构建 Android
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- name: 设置 Java
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: 设置 Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
cache: true
- run: flutter pub get
# 解码 Keystore(从 GitHub Secrets 读取 Base64 编码的 keystore)
- name: 解码签名 Keystore
run: |
echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 -d > android/app/release.keystore
- name: 构建 Android App Bundle
run: |
flutter build appbundle \
--flavor production \
--dart-define=ENV=production \
--dart-define=API_URL=${{ secrets.PROD_API_URL }} \
--obfuscate \
--split-debug-info=./debug-symbols \
--release
env:
KEYSTORE_PATH: release.keystore
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
- name: 上传构建产物
uses: actions/upload-artifact@v3
with:
name: android-release
path: build/app/outputs/bundle/productionRelease/
retention-days: 7
# ─── Job 4:构建 iOS ──────────────────────────────
build-ios:
name: 构建 iOS
runs-on: macos-14 # 必须用 macOS Runner
needs: test
steps:
- uses: actions/checkout@v4
- name: 设置 Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: ${{ env.FLUTTER_VERSION }}
cache: true
- run: flutter pub get
# 安装 Apple 证书和 Provisioning Profile
- name: 安装签名证书
uses: apple-actions/import-codesign-certs@v2
with:
p12-file-base64: ${{ secrets.IOS_P12_CERT_BASE64 }}
p12-password: ${{ secrets.IOS_P12_PASSWORD }}
- name: 安装 Provisioning Profile
uses: apple-actions/download-provisioning-profiles@v1
with:
bundle-id: com.example.app
issuer-id: ${{ secrets.APPSTORE_ISSUER_ID }}
api-key-id: ${{ secrets.APPSTORE_KEY_ID }}
api-private-key: ${{ secrets.APPSTORE_PRIVATE_KEY }}
- name: 构建 iOS
run: |
flutter build ipa \
--flavor production \
--dart-define=ENV=production \
--obfuscate \
--split-debug-info=./debug-symbols \
--release \
--export-options-plist=ios/ExportOptions.plist
- name: 上传构建产物
uses: actions/upload-artifact@v3
with:
name: ios-release
path: build/ios/ipa/
自动发布到应用商店
CD 配置(发布到 Google Play + App Store)
# .github/workflows/release.yml
name: Flutter Release
on:
push:
tags:
- 'v*.*.*' # 触发条件:推送 vX.Y.Z 格式的 tag
jobs:
release:
name: 发布到应用商店
runs-on: macos-14
needs: [build-android, build-ios] # 需要构建完成
steps:
# ─── 发布到 Google Play ────────────────────
- name: 发布到 Google Play
uses: r0adkll/upload-google-play@v1
with:
serviceAccountJsonPlainText: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT }}
packageName: com.example.app
releaseFiles: android-release/*.aab
track: internal # internal → alpha → beta → production
status: completed
whatsNewDirectory: changelogs/ # 版本更新说明
# ─── 发布到 App Store ──────────────────────
- name: 发布到 TestFlight
uses: apple-actions/upload-testflight-build@v1
with:
app-path: ios-release/*.ipa
issuer-id: ${{ secrets.APPSTORE_ISSUER_ID }}
api-key-id: ${{ secrets.APPSTORE_KEY_ID }}
api-private-key: ${{ secrets.APPSTORE_PRIVATE_KEY }}
Fastlane 自动化签名
Android Fastlane 配置
# android/fastlane/Fastfile
default_platform(:android)
platform :android do
desc "发布到 Google Play 内测轨道"
lane :internal do
# 自动递增版本号
increment_version_code(
gradle_file_path: "app/build.gradle"
)
# 构建 AAB
gradle(
task: "bundle",
flavor: "production",
build_type: "Release",
properties: {
"android.injected.signing.store.file" => ENV["KEYSTORE_PATH"],
"android.injected.signing.store.password" => ENV["KEYSTORE_PASSWORD"],
"android.injected.signing.key.alias" => ENV["KEY_ALIAS"],
"android.injected.signing.key.password" => ENV["KEY_PASSWORD"],
}
)
# 上传到 Google Play
upload_to_play_store(
track: 'internal',
aab: "app/build/outputs/bundle/productionRelease/app-production-release.aab"
)
end
end
iOS Fastlane 配置
# ios/fastlane/Fastfile
default_platform(:ios)
platform :ios do
desc "同步证书(使用 Match 管理)"
lane :certificates do
# Match:团队共享证书管理(存储在私有 Git 仓库)
match(
type: "appstore",
app_identifier: "com.example.app",
readonly: ENV["CI"] == "true" # CI 环境只读,不重新生成
)
end
desc "发布到 TestFlight"
lane :beta do
certificates
# 自动递增 Build Number
increment_build_number(
build_number: latest_testflight_build_number + 1
)
build_app(
scheme: "Runner",
configuration: "Release-production",
export_method: "app-store"
)
upload_to_testflight(
skip_waiting_for_build_processing: true
)
end
end
iOS 签名证书链
Apple 签名体系:
┌─────────────────────────────────────┐
│ Apple Root CA │ 根证书(Apple 持有)
│ └── Apple WWDR CA │ 中间证书(自动信任)
│ └── Developer Certificate │ 开发者证书(你创建)
│ │
│ Provisioning Profile │ 配置文件(绑定以下内容)
│ ├── App ID (Bundle Identifier) │ com.example.app
│ ├── Developer Certificate │ 与上面的证书关联
│ ├── Entitlements (权限) │ Push Notifications, iCloud 等
│ └── Device UDIDs (开发/Ad-hoc) │ 允许安装的设备
└─────────────────────────────────────┘
证书类型:
- Development:真机调试用
- Distribution (App Store):App Store 发布用
- Ad-hoc:指定设备测试用(最多 100 台)
- Enterprise:企业内部分发用
版本号管理策略
// pubspec.yaml 版本号格式
version: 2.3.1+42
// │ │ │ └── Build Number(整数,每次发布递增)
// │ │ └──── Patch(Bug 修复)
// │ └────── Minor(新功能,向后兼容)
// └──────── Major(破坏性变更)
// 语义化版本(Semantic Versioning)
// - MAJOR.MINOR.PATCH
// - 对应 Android versionName / iOS CFBundleShortVersionString
// + 后面的数字 = Build Number
// - 对应 Android versionCode / iOS CFBundleVersion
# 自动化版本管理脚本
#!/bin/bash
# scripts/bump_version.sh
PUBSPEC="pubspec.yaml"
CURRENT=$(grep "^version:" $PUBSPEC | cut -d' ' -f2)
VERSION=$(echo $CURRENT | cut -d'+' -f1)
BUILD=$(echo $CURRENT | cut -d'+' -f2)
NEW_BUILD=$((BUILD + 1))
NEW_VERSION="${VERSION}+${NEW_BUILD}"
# 更新 pubspec.yaml
sed -i '' "s/^version: .*/version: ${NEW_VERSION}/" $PUBSPEC
echo "版本从 $CURRENT 更新到 $NEW_VERSION"
Shorebird:热更新(Code Push)
# Shorebird 是 Flutter 的 Code Push 解决方案
# 允许在不经过 App Store 审核的情况下更新 Dart 代码
# 安装 Shorebird CLI
curl --proto '=https' --tlsv1.2 https://raw.githubusercontent.com/shorebirdtech/shorebird/main/install.sh -sSf | bash
# 初始化项目
shorebird init
# 创建发布版本(替代 flutter build)
shorebird release android
shorebird release ios
# 推送热更新补丁(无需重新审核)
shorebird patch android
shorebird patch ios
Shorebird 的限制:
| 能更新 | 不能更新 |
|---|---|
| Dart 代码逻辑 | Native 代码(Kotlin/Swift) |
| UI 布局 | Flutter 引擎版本 |
| 业务逻辑 | 资源文件(图片/字体) |
| 状态管理代码 | Manifest/Info.plist |
完整发布流水线
代码提交 → PR 创建
│
▼
[CI] lint + analyze(~2min)
│
▼
[CI] 单元测试 + Widget 测试(~5min)
│
▼(全部通过)
│
├── Push to develop → 构建 staging 包 → 发布到 Firebase App Distribution(内测)
│
└── Tag v*.*.* → 构建 release 包 → 发布到 Google Play(internal)+ TestFlight
↓
人工确认(promote to production)
↓
Google Play Production + App Store Review
过关标准
✅ 能配置多 flavor(dev/staging/prod)的构建变体
✅ 能搭建一条从代码提交到应用商店发布的完整 CI/CD 流水线
✅ 能解释 iOS 签名的证书链关系(Root CA → WWDR CA → Developer Cert → Provisioning Profile)
✅ 能配置 --dart-define 传递环境变量并在代码中读取
✅ 理解 Shorebird Code Push 能更新什么、不能更新什么
上一篇:30. 测试策略 | 下一篇:32. 包开发与插件发布