
# --dart-define keys

`flutter build apk --dart-define=SPRING_PROFILES_ACTIVE=prod` passes a value into the compiled program. For Spring for Dart to see it as a property, the `@SpringBootApplication` output lists every property name the application may read, each behind a constant check, in `springApplication.dartDefines`. This page explains why, where the names come from, and how to shorten the list.

## Why the keys must be constant

A Flutter app, a web app or an AOT executable often has no command line and no useful environment variables. Build-time defines are how such a program is configured: `--dart-define` for `flutter build` and `flutter run`, `-D` for `dart compile` and `dart run`.

But a Dart program can read a define only with a **constant expression and a literal key**:

```dart
const url = String.fromEnvironment('API_URL'); // works everywhere
```

There is no way to ask "which defines were given?" or to read a define whose name is only known at run time. On the web and in AOT builds the compiler replaces `String.fromEnvironment('API_URL')` with the value while it compiles, so the key has to be written in the source.

Spring reads properties by name at run time (`environment.getProperty('api.url')`), from names in annotations and config files. To bridge the two, the generator collects at build time every name the application may read, and writes one constant lookup per name. The runtime then has a map of the defines that were given, and serves it as a property source.

## What the generator writes

The `dartDefines:` argument of `springApplication`, an excerpt from the example of `spring_core_dart` (prefixes dropped):

```dart
SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [springBootAutoConfiguration],
  dartDefines: {
    if (const bool.hasEnvironment('DEBUG'))
      'DEBUG': const String.fromEnvironment('DEBUG'),
    if (const bool.hasEnvironment('GREETING_PUNCTUATION'))
      'GREETING_PUNCTUATION': const String.fromEnvironment(
        'GREETING_PUNCTUATION',
      ),
    if (const bool.hasEnvironment('LOGGING_LEVEL_ROOT'))
      'LOGGING_LEVEL_ROOT': const String.fromEnvironment('LOGGING_LEVEL_ROOT'),
    if (const bool.hasEnvironment('SPRING_PROFILES_ACTIVE'))
      'SPRING_PROFILES_ACTIVE': const String.fromEnvironment(
        'SPRING_PROFILES_ACTIVE',
      ),
    // ...
    if (const bool.hasEnvironment('greeting.punctuation'))
      'greeting.punctuation': const String.fromEnvironment(
        'greeting.punctuation',
      ),
    if (const bool.hasEnvironment('spring.profiles.active'))
      'spring.profiles.active': const String.fromEnvironment(
        'spring.profiles.active',
      ),
    // ...
  },
  fingerprint: !const bool.fromEnvironment('dart.vm.product')
      ? _$fingerprint
      : null,
);
```

How it works:

- Each entry is a collection `if` on a **constant** condition. When a define is not given, `const bool.hasEnvironment(...)` is `false` at compile time, and the compiler drops the entry. Only the defines you passed remain in the compiled map, so a long list costs nothing at run time.
- The keys are sorted (upper-case names sort before lower-case ones).
- `bool.hasEnvironment` tells a define given as an empty string (`--dart-define=KEY=`) from one not given at all.

At run time, `SpringApplication` puts the map into the environment as the property source `dartDefines`:

- right **below the command-line arguments**, and **above the OS environment and the config files**;
- with relaxed names, like environment variables: a define `API_URL` answers `${API_URL}` and `api.url`, and `SPRING_PROFILES_ACTIVE` activates profiles.

## The two forms of each name

Every collected name is written twice: as written (`shop.currency`) and in its environment-variable form (`SHOP_CURRENCY`). Both are literal keys, so you can pass either spelling:

```bash
flutter build web --dart-define=shop.currency=USD
flutter build web --dart-define=SHOP_CURRENCY=USD
```

The environment form is the one Spring Boot binds environment variables from:

| Name | Environment form |
|---|---|
| `shop.currency` | `SHOP_CURRENCY` |
| `shop.max-basket-size` | `SHOP_MAXBASKETSIZE` (dashes are removed) |
| `app.servers[0].host` | `APP_SERVERS_0_HOST` |
| `spring.flutter.scan-os-environment` | `SPRING_FLUTTER_SCANOSENVIRONMENT` |
| `NEON_KEYCLOAK_SECRET` | `NEON_KEYCLOAK_SECRET` (already in that form) |

The rule: upper case, `.` becomes `_`, `-` is removed, an index `[0]` becomes `_0_`, and a trailing `_` is dropped.

Only these two spellings are read. Other spellings that relaxed binding would accept elsewhere (`shop.maxBasketSize`, `SHOP_MAX_BASKET_SIZE`) are not keys in the map, so a define with such a name is not seen.

A name with characters other than letters, digits, `_`, `.`, `-`, `[` and `]` is skipped rather than escaped into the generated code.

## Where the names come from

The generator collects the names from four places.

**1. The application's scanned libraries.** In every library the `@SpringBootApplication` scan covers, and in the libraries of the nested `@ComponentScan` modules it imports (a scan root in `lib/src/` with its own module counts too):

- every `${...}` placeholder in the arguments of any annotation, on classes, constructors, parameters, fields, methods and top-level declarations. Strings inside nested constants, lists, maps and records count too. Nested placeholders give both keys (`${a:${b}}` gives `a` and `b`); a placeholder inside a key gives only the inner one (`${${env}.url}` gives `env`, since the full key is not known);
- the names of `@ConditionalOnProperty` and `@ConditionalOnBooleanProperty`, joined with their `prefix`;
- the bound names of `@ConfigurationProperties` classes: the prefix, then each constructor parameter or public field in kebab case (`maxBasketSize` → `shop.max-basket-size`), and those of nested classes of the same library.

**2. The config files.** Every file of the embedded resources whose name starts with `application` and ends in `.properties`, `.yml` or `.yaml` (`application.yml`, `application-prod.properties`, `config/application-eu.yml`): each key (YAML is flattened, `server.port`, `app.hosts[0]`) and each placeholder in a value. A YAML file that does not parse is skipped; the application reports it when it reads the file. Other files (`config/supplier.properties`) are not read.

**3. A few names that are always offered**, because they are read before or around the config files and no scanned code names them:

```text
spring.profiles.active
spring.profiles.include
spring.main.banner-mode
spring.flutter.scan-os-environment
debug
trace
logging.level.root
```

**4. Nothing else.** In particular:

- The **properties of starters** (`server.port`, `spring.datasource.url`, ...) are keys only when your config files or your scanned code name them.

To make such a property settable with `--dart-define`, name it in `application.properties` (or `application.yml`), for example with its default value:

```properties
# lib/resources/application.properties
server.port=8080
```

## Examples

A Flutter app that chooses its profile and its API at build time:

```bash
flutter build apk \
  --dart-define=SPRING_PROFILES_ACTIVE=prod \
  --dart-define=API_URL=https://api.neon.books
```

```yaml
# lib/resources/application.yml
api:
  url: http://localhost:8080   # the key makes api.url and API_URL defines
```

```dart
@Service()
class CatalogClient {
  CatalogClient(@Value(r'${api.url}') this.baseUrl);

  final String baseUrl; // https://api.neon.books in the prod build
}
```

Several values from a file (a Flutter feature; the keys are the same):

```bash
flutter run --dart-define-from-file=config/dev.json
```

An AOT executable:

```bash
dart compile exe -Dserver.port=9090 -o build/shop bin/main.dart
```

More logging for one run (`logging.level.root` is always a key):

```bash
flutter run --dart-define=LOGGING_LEVEL_ROOT=debug
```

The values are compiled into the program and can be read from it. Never pass secrets this way.

## Leaving keys out

The build option `dart_defines_exclude` takes a list of property name prefixes. The properties under them, in both forms, are not written into `dartDefines`, so a `--dart-define` does not set them. Config files, the environment and the command line still do.

```yaml
# build.yaml of your package
targets:
  $default:
    builders:
      spring_core_dart_generator:spring_core_dart:
        options:
          dart_defines_exclude: [spring.flutter.theme]
```

Use it when many keys would be listed for no purpose (a Flutter theme declared in `application.yml` gives one key per token), or when a property must not be changeable at build time.

How a prefix matches:

- **Whole segments.** `spring.datasource` leaves out `spring.datasource.url`, but not `spring.datasourceish`.
- **Relaxed, as Spring Boot binds.** Segments are compared case-insensitively, with `-` and `_` inside a segment ignored, and an index as a segment of its own. `spring.dataSource`, `spring.data-source` and `SPRING_DATASOURCE` are the same prefix.
- **Both forms together.** When either form of a property matches, both its dotted form and its environment form are left out.
- **A trailing `.` or `[` is ignored.** `spring.datasource.` is `spring.datasource`.

Invalid entries fail the build with an `ArgumentError`: an entry that is not a string, a blank entry, a wildcard (`spring.datasource.*`; a prefix already covers everything under it), or characters other than letters, digits, `_`, `.`, `-`, `[` and `]`.

## In Spring (Java)

Java programs read system properties and environment variables at run time, so Spring Boot needs nothing like this: `-Dshop.currency=USD` on the `java` command line is a property. The closest Dart equivalent of a system property is a define, and since a define can only be read with a constant key, the generator writes the keys for you.

## See also

- [@SpringBootApplication](spring-boot-application.md)
- [Options](options.md)
- [Environment](../spring-core-dart/config/environment.md)
- [Placeholders](../spring-core-dart/config/placeholders.md)
- [@ConfigurationProperties](../spring-core-dart/config/configuration-properties.md)
