coolerneo
coolerneo

Reputation: 21

How to use dart defined variables inside of AppDelegate.swift file

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"]

Upvotes: 2

Views: 1412

Answers (1)

Hakan Balcılar
Hakan Balcılar

Reputation: 7

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)

Upvotes: -1

Related Questions