Codemagic – Set Dynamic Environment Variables for the Build arguments

Issue

I am looking a way to manage dynamic environment variables in my build arguments.

enter image description here

I am able to make it work if I define values for TARGET_FILE and FLAVOR in the environment variable section in CodeMagic.
But my goal is to have the values specified in my git repository. So I will be able to change it and have a dynamic build.

I was thinking I would be able to set the env var in the pre-build section.

enter image description here

Following is a sample of my pre-build.sh file

# in my case it’s `dev`, `qa` and `prod`
export FLAVOR='qa'

# major and minor part of app version e.g. 1.0
export VERSION_NUMBER='1.0.0'

# this is the entry point of the app e.g. main_dev.dart
export TARGET_FILE="lib/main_$FLAVOR.dart"

My build is still failing because the TARGET_FILE for example is not specified

Target file "--flavor" not found.


Build failed :|
Failed to build for Android

I was wondering if anyone has ever encountered this scenario

Solution

As for configuring build from GitHub you can use codemagic.yaml file that allows you to define the configuration for CodeMagic build, including env variables (here is a docs).

Additional notes, just a proposition))

I actually don’t know what is going on in your Flavors and env entry points, but quite possible you can actually get rid of both.

For instance, you can use .env file and flutter_config package to pass env specific variables to the native layer, including plist’s and Gradle. Also, you can load this .env file into Dart code and use variables from it. On top of this, you can use this package to generate .env file with the terminal command (if you don’t want to create any sh scripts))). Alongside with .env file, it can generate Dart class specifically for Dart code. It also can generate files based on global env variables.

In that way all environment specific configuration will be defined once, you won’t expose your prod credentials anywhere except build tool and you won’t need to copy/paste multiple entry points.

Update 08/05/2020:

Starting from Flutter 1.17 you can use --dart-defines argument instead of environment_config and flutter_config package to define compile-time variables. You can read more about this argument here

Answered By – tatsuDn

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *