Search code examples
androidfluttergradlegoogle-maps-api-3

environment variables in FLutter


I am working on a Flutter project with Google Maps. I have an API Key and as per the documentation we should not put it directly in the AndroidManifest.xml or build.grafle file.

I came accross this snippet of code in a github project and I cannot really understand it. I am not that good in gradle.

def dartEnvironmentVariables = []
   if (project.hasProperty('dart-defines')) {
       dartEnvironmentVariables = project.property('dart-defines')
          .split(',')
          .collectEntries { entry ->
             def pair = new String(entry.decodeBase64(), 'UTF-8').split('=')
             [(pair.first()): pair.last()]
    }
}

My question is, where should dart-defines be within the project structure. I couldn't find any in the github project. And what could such a file look like?

I want to store the Goole Maps API KEY there such that I could use it in my build.gradle file as follows:

manifestPlaceholders.ANDROID_GOOGLE_MAPS_API_KEY = dartEnvironmentVariables.ANDROID_GOOGLE_MAPS_API_KEYs

And then in AndroidManifest.xml:

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

Solution

  • dart-defines is passed at the command line ,

    So flutter build apk --dart-defines ANDROID_GOOGLE_MAPS_API_KEY=your_key

    Or flutter run --dart-defines ANDROID_GOOGLE_MAPS_API_KEY=your_key


    As of Flutter 3.19 you can make a config.json file, like this:

    {
      "ANDROID_GOOGLE_MAPS_API_KEY": "your_key"
    }
    

    And then access that in a similar manner but with dart-define-from-file,

    eg. flutter build apk --dart-define-from-file=config.json


    See: https://itnext.io/flutter-1-17-no-more-flavors-no-more-ios-schemas-command-argument-that-solves-everything-8b145ed4285d and https://itnext.io/flutter-3-7-and-a-new-way-of-defining-compile-time-variables-f63db8a4f6e2