2

I am using Google Maps for Flutter to access a map in my application. To make it usable for iOS I need to provide the API key inside of AppDelegate.swift as:

GMSServices.provideAPIKey(GOOGLE_MAPS_API_KEY)

My application will be deployed later, so I cannot just leave the API key in the open and I want to access it as a dart defined variable. For example, thats how I would be running my code and setting the dart defined variable:

flutter run --dart-define=GOOGLE_MAPS_API_KEY=apiKey

Question: How can I access this dart defined variable from the AppDelegate.swift file so that I can register the API key for the Google Maps Service? I haven't found any way to debug this, so every time I start an application and try to access GoogleMap widget it automatically crashes without any possibility to catch an error.

I've tried getting the dart defined variables like this, but it is always an empty object:

ProcessInfo.processInfo.environment["DART_DEFINES"]
or 
ProcessInfo.processInfo.environment["GOOGLE_MAPS_API_KEY"]
coolerneo
  • 21
  • 2
  • Does this answer your question? [Hide Google Maps API key from source control in a Flutter app](https://stackoverflow.com/questions/57575973/hide-google-maps-api-key-from-source-control-in-a-flutter-app) – Robert Sandberg Apr 26 '23 at 09:35
  • @RobertSandberg not really, the solution given there is kind of what I have for android, but iOS doesn't work. Ideally I don't want to have an env file and store they key there, because I would be storing those keys on azure where they will be taken from when the app is built. – coolerneo Apr 26 '23 at 10:18
  • Did you find any solution on this issue? @coolerneo – CyberHunter Jun 23 '23 at 17:18
  • @CyberHunter No I haven't managed to find anything, I went for the less ideal solution to just plug the API key into there, but secure it with restrictions of my needed scope. – coolerneo Jul 11 '23 at 15:33

1 Answers1

0

First you have to define variables in the info.plist that you want to use.

like this:

<key>GOOGLE_MAPS_API_KEY</key>
<string>$(GOOGLE_MAPS_API_KEY)</string>

then you can use the following enum

public enum Environment {
    enum Keys {
        static let googleMapsApiKey = "GOOGLE_MAPS_API_KEY"
    }

    ///Get info.plist
    private static let infoDictionary: [String: Any] = { 
        guard let dict = Bundle.main.infoDictionary else {
            fatalError("Info.plist file not found")
        }
        return dict
    }()

    ///Get variables
    static let googleMapsApiKey: String = {
        guard let googleMapsApiKeyString = Environment.infoDictionary [Keys.googleMapsApiKey] as? String else { 
            fatalError("GOOGLE_MAPS_API_KEY not set in plist")
        }
        return googleMapsApiKeyString
    }()

}

and then just use the variable

GMSServices.provideAPIKey(Environment.googleMapsApiKey)