在 Flutter 配置 Github Action,打开项目的根目录中设置一个新的目录和文件 .github/workflows/deploy.yml

这是此次要实现的GitHub Actions的大致工作流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
+----------------+         +------------------+         +-----------------+
| | | | | |
| 触发事件 +-------->+ 准备环境 +-------->+ 构建与测试 |
| (push 或 PR) | | (确定 Flutter | | (构建 APK 和 |
| | | 版本) | | iOS 应用,运行 |
+----------------+ +------------------+ | 测试) |
+--------+--------+
|
|
v
+--------+--------+
| |
| 部署 |
| (上传构建产物到 |
| 生产环境) |
| |
+-----------------+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
name: Flutter CI/CD Pipeline

on:
push:
branches: [ main ]
tags:
- 'v*' # 只有带有特定版本格式(如v1.0)的标签才会触发此工作流
pull_request:
branches: [ main ] # 只有针对 main 分支的 PR 才会触发此工作流

jobs:
prepare:
runs-on: ubuntu-latest
outputs:
flutter_version: '2.2.3'
steps:
- name: Determine Flutter version
run: echo "::set-output name=flutter_version::2.2.3" # 设置 Flutter 版本,以便后续任务使用

build_and_test:
needs: prepare
runs-on: ubuntu-latest
strategy:
matrix:
platform: [apk, ios]
include:
- platform: apk
os: ubuntu-latest
- platform: ios
os: macos-latest
steps:
- name: Checkout code
uses: actions/checkout@v2 # 检出仓库代码
- name: Setup Flutter
uses: subosito/flutter-action@v1
with:
flutter-version: ${{ needs.prepare.outputs.flutter_version }} # 使用之前确定的 Flutter 版本
- name: Install dependencies
run: flutter pub get # 安装 Flutter 项目依赖
- name: Run tests
run: flutter test # 运行所有测试
- name: Build
run: |
if [ "${{ matrix.platform }}" == "apk" ]; then
flutter build apk --release # 构建 Android APK
else
flutter build ios --release --no-codesign # 构建 iOS 应用,无需代码签名
shell: bash
- name: Archive Artifacts
uses: actions/upload-artifact@v2
with:
name: ${{ matrix.platform }}-release
path: |
build/app/outputs/flutter-apk/*.apk
build/ios/iphoneos/*.app

deploy:
needs: build_and_test
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Download Artifacts
uses: actions/download-artifact@v2
with:
name: apk-release
- name: Deploy
run: |
VERSION=${GITHUB_REF#refs/tags/}
echo "Deploying version $VERSION to production"
# 这里可以添加具体的部署命令,例如上传到应用商店或服务器