首页 > 解决方案 > Flutter iOS 上每种风味构建的不同 google maps api 密钥

问题描述

正如我从google_maps_flutter文档中了解到的那样,我们需要在内部声明 google maps api 密钥,AppDelegate.swift如下所示:

GMSServices.provideAPIKey("YOUR KEY HERE")

有没有办法为每个风味构建使用不同的 api 密钥?例如,用于开发和生产的不同 api 密钥

标签: iosxcodeflutter

解决方案


我使用主动编译条件来解决这个问题:

  1. 在 Xcode 中,转到 PROJECT -> Runner -> Build Settings 并搜索“活动编译条件”。为每种不同的风味添加一个文本值。主动编译条件

  2. 在 中AppDelegate.swift,添加预处理器条件语句以针对不同的风格执行不同的代码,在我们的例子中提供不同的 API 密钥:

    import UIKit
    import Flutter
    import GoogleMaps
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
    
        // Using active compilation conditions to provide the right API key for the right flavor.
        #if DEV
            GMSServices.provideAPIKey("<API key for DEV project>")
        #elseif QA
            GMSServices.provideAPIKey("<API key for QA project>")
        #elseif PROD
            GMSServices.provideAPIKey("<API key for PROD project>")
        #endif
    
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    

推荐阅读