Load api key to AndroidManifest.xml from .env file in flutter

The below steps enabled me to acess my env variables from flutter code, android code and ios code from the same .env file :

1.Install the package flutter_config by adding to your project's pubspec.yaml file like below

dependencies:
  flutter_config: ^1.0.8

2.Create a .env file at the root of your project and add your env variables to it

GOOGLE_MAPS_API_KEY=googlemapsapikey
FABRIC_ID=abcdefgh

3.Initialize plugin in your main function

import 'package:flutter_config/flutter_config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // Required by FlutterConfig
  await FlutterConfig.loadEnvVariables();

  runApp(MyApp());
}

4.Now access your env variables anywhere in your dart code

import 'package:flutter_config/flutter_config.dart';

FlutterConfig.get('FABRIC_ID')
  1. Access your env variables in your project's android files.

First, You need to manually apply a plugin to your app, from android/app/build.gradle: Right below apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" add the following line: apply from: project(':flutter_config').projectDir.getPath() + "/dotenv.gradle"

In my case I needed to access the google maps api key in AndroidManifest.xml file like

`<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/GOOGLE_MAPS_API_KEY" />`

You can also acccess your env variables in your gradle files and Java/Kotlin Code. For more details refer the docs

6.Access your env variable from your projects ios files: In my case I needed to access the maps api key from AppDelegate.swift like

import flutter_config
FlutterConfigPlugin.env(for: "GOOGLE_MAPS_API_KEY")

Its also possible to access your env variables from your Obj-C classes, Build settings and Info.plist. For more details refer the docs

Building a release version

When building your apk for release, the R8 code shrinker obfuscates the BuildConfig class which holds all the env variables and thus causes all the env variables to be null. To prevent this, the following has to be done:

  1. Add file android/app/proguard-rules.pro to your app's project.
  2. Add the below line to the newly created proguard-rules.pro file:

-keep class com.yourcompany.app.BuildConfig { *; }

where com.yourcompany.app should be replaced with your app's package name.


The below video has a nice explanation of how we can Load API key to AndroidManifest.xml from the .env file in Flutter.

The change here is, we need to add a different plugin to make it work and follow the steps mentioned in the video tutorial.

Plugin https://pub.dev/packages/flutter_config

Video https://www.youtube.com/watch?v=OtkrNQxJzBQ

Github https://github.com/ByneappLLC/flutter_config/blob/master/doc/ANDROID.md