generateEnvClass static method
Generates the AppEnvironment class and updates pubspec.yaml with the selected environment's version.
- If
envArgumentis provided, it uses that environment. - Otherwise, it defaults to the
current_environmentvalue inenvironment.yaml.
The function does the following:
- Reads the
environment.yamlfile. - Determines the selected environment.
- Retrieves the environment-specific version.
- Updates
pubspec.yamlwith the correct version. - Generates a
lib/app_environment.dartclass with environment variables.
Example usage:
void main() async {
await EnvManager.generateEnvClass();
}
If the selected environment is marked as isProdEnv: true, the version format is:
version: 1.0.0
Otherwise, the version format is:
version: 1.0.0-staging // Example for staging
Implementation
static Future<void> generateEnvClass([String? envArgument]) async {
final envFile = File(envFileName);
if (!await envFile.exists()) {
await _createDefaultEnvFile(envFile);
}
final yamlString = await envFile.readAsString();
final yamlMap = loadYaml(yamlString);
final currentEnv = envArgument ?? yamlMap['current_environment'];
final environments = yamlMap['environments'] as Map;
if (!environments.containsKey(currentEnv)) {
print('Error: Environment "$currentEnv" does not exist in $envFileName.');
exit(1);
}
final envConfig = environments[currentEnv] as YamlMap;
final baseVersion = envConfig['version'] ?? '1.0.0';
// Determine if the environment is production
var isProdEnv = false;
if (envConfig.containsKey("isProdEnv")) {
isProdEnv = envConfig['isProdEnv'] == true;
}
// Format version based on `isProdEnv`
final formattedVersion =
isProdEnv ? baseVersion : '$baseVersion-$currentEnv';
// Update `pubspec.yaml` with the selected environment version
await _updatePubspecVersion(formattedVersion);
// Generate the AppEnvironment class dynamically
final classContent = '''
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT EDIT.
/// Contains environment variables and app configuration.
class AppEnvironment {
/// The current selected environment.
static const String currentEnvironment = '$currentEnv';
/// The application version from `environment.yaml`.
static const String version = '$formattedVersion';
${_generateStaticVariables(envConfig)}
}
''';
final classFile = File(envClassFileName);
await classFile.writeAsString(classContent);
print('Environment class generated successfully.');
}