I am using the flutter_dotenv
[https://pub.dev/packages/flutter_dotenv] package and defines a .env
file to define my environment variables. But for using google maps I also have to use maps apikey in AndroidManifest.xml
file. Is it possible to read the maps apikey from .env
file of the flutter_dotenv
package instead of hardcoding the apikey in AndroidManifest.xml
file?
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')
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
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:
-keep class com.yourcompany.app.BuildConfig { *; }
where com.yourcompany.app should be replaced with your app's package name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With