Hide Google Maps API key from source control in a

2020-07-16 09:33发布

To enable the Google Maps SDK you must update: android/app/src/main/AndroidManifest.xml for android, and ios/Runner/AppDelegate.m for ios with your API key.

The problem:

I don't want to check in my API key into source control.

Is there a way to hide this key with a .env file and .gitignore?

What is best practice here?

3条回答
乱世女痞
2楼-- · 2020-07-16 09:46

Starting from Flutter 1.17 you can use compile-time variables for this. Just use --dart-define key in flutter run or flutter build commands. Then you can use them in your iOS or Android code. Here is an article with some explanation and samples

查看更多
我命由我不由天
3楼-- · 2020-07-16 09:58

You can set your api keys as environment variables which can be read during build on your local machine only. Create an env variable MAPS_API_KEY="your-key-here", then add these lines to [your-project]/android/app/build.gradle

 defaultConfig {
        manifestPlaceholders = [mapsApiKey: "$System.env.MAPS_API_KEY"]
    }

and then you can use the mapsApiKeys to pass your api keys in AndroidManifest.xml

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

For ios, add these to AppDelegate.m

NSString* mapsApiKey = [[NSProcessInfo processInfo] environment[@"MAPS_API_KEY"];

[GMSServices provideAPIKey:mapsApiKey];
查看更多
▲ chillily
4楼-- · 2020-07-16 10:03

You can save your keys in a separate file, and add that file to .gitignore. Then if you push your files to the repository, that file will be ignored.

In case you have a new colleague, who needs to start working on the same project, you will need to share this file with them. After checking out the project from the repository, they will need to place that file in the same directory as it was originally.

查看更多
登录 后发表回答