Flutter怎么打包与发布应用?

文章导读
本节将介绍如何将 Flutter 应用打包发布到各个平台。
📋 目录
  1. 构建准备
  2. 实例:发布配置
  3. 实例:Android 配置
  4. Android 构建
  5. iOS 构建
  6. Web 构建
  7. 实例:Web 配置
  8. 桌面应用构建
A A

Flutter 打包与发布

本节将介绍如何将 Flutter 应用打包发布到各个平台。


构建准备

在发布前,确保应用配置正确。

pubspec.yaml 配置

实例:发布配置

# 应用信息
name
: my_app
description
: "我的 Flutter 应用"
version
: 1.0.0+1  # 版本号(重要!)

# 应用图标
flutter
:
  uses-material-design
: true
  # 生成图标需要 flutter pub run flutter_launcher_icons

Android 配置

修改 android/app/build.gradle 中的应用配置:

实例:Android 配置

// android/app/build.gradle

android {
    namespace "com.example.myapp"
    compileSdk = 34

    defaultConfig {
        applicationId "com.example.myapp"  // 应用 ID
        minSdk = 21                          // 最低 Android 版本
        targetSdk = 34                       // 目标版本
        versionCode 1                        // 版本代码(每次发布递增)
        versionName "1.0.0"                  // 版本名称
    }

    signingConfigs {
        release {
            // 发布签名配置
            storeFile file("key.jks")
            storePassword "密码"
            keyAlias "别名"
            keyPassword "密钥密码"
        }
    }
}

Android 构建

构建 APK

# 调试 APK
$ flutter build apk --debug

# 发布 APK
$ flutter build apk --release

# 带签名(需要配置 signingConfigs)
$ flutter build apk --release --target-platform android-arm64

构建 App Bundle

# 构建 App Bundle(推荐用于 Google Play)
$ flutter build appbundle --release

iOS 构建

准备工作

  • 安装 Xcode
  • 配置 Apple 开发者账号
  • 创建 App ID 和证书

命令行构建

# 模拟器版本
$ flutter build ios --simulator --no-codesign

# 发布版本(需要签名)
$ flutter build ipa --release

使用 Xcode 构建

  1. 在 ios/ 目录打开 .xcworkspace 文件
  2. 选择目标设备和 Signing 配置
  3. 点击 Product > Archive

Web 构建

# 构建 Web 版本
$ flutter build web --release

# 输出目录:build/web/

Web 配置

在 web/index.html 中配置应用:

实例:Web 配置

<!DOCTYPE html>
<html>
<head>
  <base href="/">
  <title>我的应用</title>
  <meta name="description" content="Flutter 应用">
  <!-- PWA 支持 -->
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <script src="flutter.js" defer></script>
</body>
</html>

桌面应用构建

# Windows
$ flutter build windows --release

# macOS
$ flutter build macos --release

# Linux
$ flutter build linux --release

发布前务必测试应用的发布版本,调试版本可能包含额外的调试信息。