Monday, June 12, 2023

How to Inject External Configuration Values when Building Flutter Apps in VSCode

Injecting External Configuration Values at Build Time in Flutter

This post will guide you on how to inject external configuration values at build time in Flutter. These methods are especially useful for managing dynamic environment variables. The most common method is using the --dart-define option.

Utilizing the --dart-define Option to Define Dart Variables

The --dart-define option helps define Dart variables and pass their values. The following example demonstrates how to define a Dart variable named version and assigns the current date and time as its value.

flutter build apk --profile --dart-define=version=`date +%d_%H:%M:%S`

Within your Dart code, you can reference this value using the String.fromEnvironment() function:

String.fromEnvironment("version")

Automating the `--dart-define` Option via `launch.json` File

Manually inputting values into the `--dart-define` option can be tedious. You can automate this process using the `launch.json` file in Visual Studio Code.


{
    "version": "0.2.0",
    "configurations": [      
      {                	        
        "name": "Flutter build apk with version",                            
        "request": "launch",                            
        "type": "dart",                            
        "program": "..\\lib\\main.dart",                            
        "flutterMode":"profile",           	                    
        "toolArgs" : ["--dart-define=version=`date +%d_%H:%M:%S`"]
      }
    ]
}

By adding the `--dart-define=version=date +%d_%H:%M:%S` option into the `toolArgs` array, the value is automatically entered at each build process.

Employing Build Environment Variables in Dart Code

In your Dart code, you can retrieve the `version` value defined earlier using the `String.fromEnvironment()` function:


static const version = String.fromEnvironment("version", defaultValue: '');

This `version` variable can be used for various purposes within your app. For instance, it could be displayed as the app version name on an About page.


0 개의 댓글:

Post a Comment