You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开源项目中如何在原生配置文件使用.env的Google Maps API密钥

Flutter Google Maps API密钥原生配置隐藏方案

Android 端配置

AndroidManifest无法直接读取.env文件,需要借助Gradle注入变量:

  1. 确保根目录.env文件配置正确
    项目根目录的.env文件中添加:

    API_KEY=你的Google Maps API密钥
    
  2. 修改Android构建脚本
    打开android/app/build.gradle,在android代码块外部添加加载.env的逻辑:

    def dotenv = new Properties()
    dotenv.load(new FileInputStream(rootProject.file('.env')))
    

    接着在defaultConfig中添加占位符配置:

    defaultConfig {
        // 保留原有其他配置
        manifestPlaceholders = [GOOGLE_MAPS_API_KEY: dotenv['API_KEY']]
    }
    
  3. 更新AndroidManifest.xml
    将硬编码的密钥替换为Gradle注入的变量:

    <application>
        <meta-data android:name="com.google.android.geo.API_KEY"
                   android:value="${GOOGLE_MAPS_API_KEY}"/>
    </application>
    

iOS 端配置

通过构建脚本+Xcode配置实现密钥注入:

  1. 创建.env读取脚本
    在ios目录下新建load_env.sh脚本,内容如下:

    #!/bin/bash
    ENV_FILE="../.env"
    XCCONFIG_FILE="Runner/Env.xcconfig"
    
    echo "" > $XCCONFIG_FILE
    API_KEY=$(grep -E '^API_KEY=' $ENV_FILE | cut -d '=' -f2-)
    echo "GOOGLE_MAPS_API_KEY = $API_KEY" >> $XCCONFIG_FILE
    

    给脚本添加执行权限:

    chmod +x ios/load_env.sh
    
  2. 配置Xcode构建阶段
    打开ios/Runner.xcworkspace,进入Runner target的Build Phases:

    • 点击左上角+号,选择New Run Script Phase
    • 将该阶段拖动到Compile Sources之前
    • 在脚本输入框填写:${SRCROOT}/load_env.sh
  3. 关联Xcode配置文件
    进入Runner target的Build Settings,找到Configuration Files:

    • 给Debug和Release模式都选择Env.xcconfig(路径自动识别,若未出现可手动指定)
  4. 更新AppDelegate.swift
    替换硬编码密钥为从配置中读取:

    import UIKit
    import Flutter
    import GoogleMaps
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
        guard let apiKey = Bundle.main.object(forInfoDictionaryKey: "GOOGLE_MAPS_API_KEY") as? String else {
          fatalError("API_KEY未在配置中找到")
        }
        GMSServices.provideAPIKey(apiKey)
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    

注意事项

  • 确认.env已加入.gitignore,避免密钥提交到仓库
  • 修改原生配置后需重新构建项目,热重载不会生效
  • iOS端首次配置后,建议清理Xcode缓存再编译

内容的提问来源于stack exchange,提问作者senabdulgani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:02:36