
# Typed keys: context.theme and context.messages

The builder `spring_flutter_keys` reads the configuration of a Flutter app and writes two Dart files with a typed getter for each key:

- `lib/spring_gen/theme.spring.keys.dart`: `context.theme`, the keys of `spring.flutter.theme.*`;
- `lib/spring_gen/messages.spring.keys.dart`: `context.messages`, the keys of the message files.

```dart
context.theme.colors.surfaceContainerLow   // Color
context.theme.spacing.m                    // double
context.theme.tokens.brand.accent          // Color
context.messages.basket.total(price)       // String
```

The files hold the **keys**, not the values. Each getter reads its value at run time from the active theme or the message source, so changing a value, switching themes or switching languages needs no new build. Only adding, removing or renaming a key does.

## Why

Without the generated files, widget code names keys as strings:

```dart
SpringTheme.of(context).color('surface-container-low');
context.message('basket.total', args: [price]);
```

A typo, or a key renamed in `application.yml`, is found only when that line runs, maybe in a screen nobody opened. With the typed keys, the same mistake is a compile error, and the editor completes the keys and shows each one's type. Spring (Java) has nothing like it: Java code reads these keys by string.

## When it runs

The builder runs for a package whose `pubspec.yaml` has, in `dependencies` or `dev_dependencies`, a package whose name starts with `spring_boot_starter_flutter`. That includes the security and navigation starters for Flutter, which bring the Flutter starter. Any other package gets nothing.

It reads:

1. every `.properties`, `.yml` and `.yaml` file of `lib/resources/`, whatever its profile (`application.yml`, `application-web.yml`, `application-dev.properties` ...);
2. the files that `spring.config.import` names with the `resources:` prefix (`optional:` allowed, a `[hint]` dropped) when they are not in the package itself. They are looked for in `lib/resources/` of each package of `dependencies`, and what they import is followed the same way. This is how an app reads a theme a library ships, such as `resources:themes/neon.yml`. Globs (`*`) and other prefixes are not followed. A file nobody has is skipped; the app reports it when it starts.

The keys are the **union** of every file, profile and theme. A key declared only in `application-dev.yml`, or only in the theme `ocean`, still gets its getter: the getter exists in every build, and the value comes from whichever theme is active.

A file that does not parse is a warning (`lib/resources/application.yml does not parse (...): its keys are not typed.`) and is skipped.

Each file is written only when it has something in it: `theme.spring.keys.dart` when there is at least one `spring.flutter.theme.*` property (or a [loader kind of the app's own](index.md#loader-kinds-of-the-apps-own)), `messages.spring.keys.dart` when there is at least one message file. The two files are declared outputs, so when the builder does not write one, `build_runner` removes the old one.

## Which library the files belong to

The two files are `part of` a generated library, not libraries of their own: they need no imports, and their classes have private constructors that only that library can call. The parent is the `.spring.dart` of the package's root library:

1. the library with `@SpringBootApplication`, if there is one;
2. else the outermost library with `@ComponentScan`: the one whose directory holds all the others. Nested scans, as in `lib/src/feature/`, are fine.

For an app, that is usually `lib/main.dart`, so the parent is `lib/spring_gen/main.spring.dart`:

```text
lib/
  main.dart                 # yours, with @SpringBootApplication or @ComponentScan
  spring_gen/
    main.spring.dart        # generated by the main builder: the beans, and the part lines
    theme.spring.keys.dart       # generated: part of 'main.spring.dart'
    messages.spring.keys.dart    # generated: part of 'main.spring.dart'
```

The main builder writes the `part` lines and the two imports the parts need (`package:flutter/widgets.dart` and `package:spring_boot_starter_flutter/spring_boot_starter_flutter.dart`) into the parent:

```dart
// lib/spring_gen/main.spring.dart (generated)
import 'package:flutter/widgets.dart';
import 'package:spring_boot_starter_flutter/spring_boot_starter_flutter.dart';
// ... the other imports

part 'messages.spring.keys.dart';
part 'theme.spring.keys.dart';
```

Widgets import `spring_gen/main.spring.dart` and get `context.theme` and `context.messages`.

A part cannot be probed with `canRead` from another build phase, so the main builder does not look for the files: it repeats the keys builder's computation to know which of the two exist. For this reason, do not disable `spring_flutter_keys` while the main builder runs, or the parent would name parts that are never written.

A library package has its own parent, such as `lib/spring_gen/spring_auto_configuration.spring.dart`, and its own keys. An app never sees the keys of a library it uses; it gets the keys of an imported theme by reading the theme's file, as above.

| Situation | Result |
|---|---|
| Two libraries with `@SpringBootApplication` | Error: `A package has one @SpringBootApplication library for the typed keys, found lib/a.dart and lib/b.dart: remove one, or move it into its own package.` |
| `@ComponentScan` libraries in unrelated directories, or two in one directory | Error: `A package has one outermost @ComponentScan library for the typed keys, found unrelated lib/a/one.dart and lib/b/two.dart: nest one scan inside the other's directory, or move one into its own package.` |
| No library with either annotation | A warning says why, and no key file is written. |

The annotations are found in the source text, at the start of a line, so a commented-out `// @ComponentScan()` does not count.

## Example

```yaml
# lib/resources/application.yml
spring:
  flutter:
    theme:
      seed-color: teal
      colors:
        surface-container-low: grey.shade100
      spacing: { s: 8, m: 16, 2xl: 48 }
      typography:
        code: { size: 13 }
      tokens:
        brand:
          accent: '#FF6B00'
          banner: { source: https://cdn.example.com/banner.jpg, refresh: 1d }
        modal:
          width: 460
          delay: 250ms
          border:
            colors: [$brand.accent, white]
            glow: { color: $colors.primary, alpha: 12% }
      styles:
        neon-chip:
          padding: [12, 6]
          radius: 2
          fill:
            default: transparent
            selected: { color: $brand.accent, alpha: 12% }
          transition: 120ms ease-out
      motion:
        durations: { fast: 120ms }
        curves: { out: ease-out }
      animations:
        glow-pulse: { duration: 1.6s, repeat: reverse }
      themes:
        ocean:
          extends: dark
          seed-color: indigo
```

```properties
# lib/resources/messages.properties
basket.title=Your basket
basket.total=Total: {0}
basket.line={0} x {1}
```

```properties
# lib/resources/messages_ja.properties
basket.title=買い物かご
basket.total=合計: {0}
```

The build log shows one warning, `lib/resources/messages_ja.properties: basket.line is missing (it is in messages.properties).`, and the builder writes the two files below. They are the builder's real output for these inputs; only the first lines of the theme file and some classes are left out where marked.

```dart
// lib/spring_gen/theme.spring.keys.dart (generated)
// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from the configuration of lib/resources/
// (spring.flutter.theme.*).

// ignore_for_file: type=lint

part of 'main.spring.dart';

/// Typed access to `spring.flutter.theme.*` from any widget.
extension SpringThemeKeys on BuildContext {
  /// The values `spring.flutter.theme.*` declares, from the active
  /// Spring theme; the widget rebuilds when it changes.
  AppTheme get theme => AppTheme._(
    ThemeKeyReader(
      SpringTheme.of(this),
      reduceMotion: MediaQuery.maybeDisableAnimationsOf(this) ?? false,
    ),
  );
}

/// The values `spring.flutter.theme.*` declares, of the
/// active Spring theme: `context.theme`.
final class AppTheme {
  const AppTheme._(this._values);
  final ThemeKeyReader _values;
  AppThemeColors get colors => AppThemeColors._(_values);
  AppThemeSpacing get spacing => AppThemeSpacing._(_values);
  AppThemeTypography get typography => AppThemeTypography._(_values);
  AppThemeTokens get tokens => AppThemeTokens._(_values);
  AppThemeStyles get styles => AppThemeStyles._(_values);
  AppThemeMotion get motion => AppThemeMotion._(_values);
  AppThemeAnimations get animations => AppThemeAnimations._(_values);
}

/// `colors.*` of the active theme.
final class AppThemeColors {
  const AppThemeColors._(this._values);
  final ThemeKeyReader _values;

  /// `colors.surface-container-low`
  Color get surfaceContainerLow => _values.color('surface-container-low');
}

/// `spacing.*` of the active theme.
final class AppThemeSpacing {
  const AppThemeSpacing._(this._values);
  final ThemeKeyReader _values;

  /// `spacing.2xl`
  double get $2xl => _values.spacing('2xl');

  /// `spacing.m`
  double get m => _values.spacing('m');

  /// `spacing.s`
  double get s => _values.spacing('s');
}

/// `tokens.brand.*` of the active theme.
final class AppThemeTokensBrand {
  const AppThemeTokensBrand._(this._values);
  final ThemeKeyReader _values;

  /// `tokens.brand.accent`
  Color get accent => _values.tokenColor('brand.accent');

  /// `tokens.brand.banner`
  ThemeImage get banner => _values.tokenImage('brand.banner');
}

/// `tokens.modal.border.*` of the active theme.
final class AppThemeTokensModalBorder {
  const AppThemeTokensModalBorder._(this._values);
  final ThemeKeyReader _values;

  /// `tokens.modal.border.colors`
  List<Color> get colors => _values.tokenColors('modal.border.colors');

  /// `tokens.modal.border.glow`
  Color get glow => _values.tokenColor('modal.border.glow');
}

// ... AppThemeTypography, AppThemeTokens, AppThemeTokensModal, the styles,
// motion and animations: shown in the sections below

/// The names of the themes, for `ThemeSelection.select`.
abstract final class AppThemes {
  /// The theme `dark`.
  static const String dark = 'dark';

  /// The theme `light`.
  static const String light = 'light';

  /// The theme `ocean`.
  static const String ocean = 'ocean';

  /// The theme `system`.
  static const String system = 'system';
}
```

```dart
// lib/spring_gen/messages.spring.keys.dart (generated; header and part of as above)

/// Typed access to the messages from any widget.
extension SpringMessageKeys on BuildContext {
  /// The messages, in the current language; the widget rebuilds when it
  /// changes.
  AppMessages get messages => AppMessages._(this);
}

/// The messages of the message files: `context.messages`.
final class AppMessages {
  const AppMessages._(this._context);
  final BuildContext _context;

  /// The messages `basket.*`.
  AppMessagesBasket get basket => AppMessagesBasket._(_context);
}

/// The messages `basket.*`.
final class AppMessagesBasket {
  const AppMessagesBasket._(this._context);
  final BuildContext _context;

  /// `basket.line`: {0} x {1}
  String line(Object? arg0, Object? arg1) =>
      _context.message('basket.line', args: [arg0, arg1]);

  /// `basket.title`: Your basket
  String get title => _context.message('basket.title');

  /// `basket.total`: Total: {0}
  String total(Object? arg0) =>
      _context.message('basket.total', args: [arg0]);
}
```

In a widget:

```dart
@override
Widget build(BuildContext context) {
  final theme = context.theme;
  return Container(
    color: theme.colors.surfaceContainerLow,
    padding: EdgeInsets.all(theme.spacing.m),
    child: Text(
      context.messages.basket.total(42),
      style: theme.typography.code,
    ),
  );
}
```

`context.theme` reads `SpringTheme.of(context)`, so the widget rebuilds when the theme changes. `context.messages` reads the current language through `context.message`, so it rebuilds when the language changes.

## The theme: `context.theme`

`AppTheme` has one getter per section the configuration uses. A section nobody declares gets no getter and no class: an app without `motion` has no `context.theme.motion`.

| Section | Getter | Type of each key | Read with |
|---|---|---|---|
| `colors.<name>` | `colors` (`AppThemeColors`) | `Color` | `_values.color('<name>')` |
| `spacing.<name>` | `spacing` (`AppThemeSpacing`) | `double` | `_values.spacing('<name>')` |
| `typography.<style>.<property>` | `typography` (`AppThemeTypography`) | `TextStyle` | `_values.textStyle('<style>')` |
| `tokens.<group>...<key>` | `tokens` (`AppThemeTokens`), a class per group | By the value: see below | `_values.tokenColor(...)`, `tokenNumber`, ... |
| `styles.<name>.<property>` | `styles` (`AppThemeStyles`) | `AppStyle<Name>`, a `ThemeStyle` | `_values.style('<name>')` |
| `motion.durations.<name>` | `motion` (`AppThemeMotion`) | `Duration` | `_values.motionDuration('<name>')` |
| `motion.curves.<name>` | `motion.curves` (`AppThemeMotionCurves`) | `Curve` | `_values.motionCurve('<name>')` |
| `animations.<name>.<property>` | `animations` (`AppThemeAnimations`) | `AnimationSpec` | `_values.animation('<name>')` |
| `loaders.<name>` | `loaders` (`AppThemeLoaders`) | `ThemeLoaderSpec` | `_values.loader('<name>')` |
| `background` | `background` | `ThemeBackgroundData?` | `_values.theme.background` |
| `splash` | `splash` | `ThemeSplashData` | `_values.splash()` |

Inside the class of a section, the getters are sorted by their Dart name.

### `colors`

Only the colors the configuration declares get a getter. The roles a theme has without declaring them (Material 3's, made from `seed-color` or Flutter's baseline) are reachable with `SpringTheme.of(context).colorScheme`, which has every role in any app, and in references as `$colors.<role>`, but they get no getter of their own. `Theme.of(context).colorScheme` has them only in a Material app. A theme with `seed-color` needs a design starter (`spring_boot_starter_flutter_material` or `spring_boot_starter_flutter_cupertino`), which makes the palette.

A value under `colors.<name>` must be a color; anything else is an error: `spring.flutter.theme.colors.link: a color is expected, found number.`

### `spacing`

Every `spacing.<name>` is a `double`, whatever is written.

### `typography`

Only the 15 text styles of the type scale (`display-large` ... `label-small`, Material 3's names) and `code`, and only when at least one property of the style is set (`typography.code.size: 13`). Other keys under `typography` (the font family, for example) get no getter.

### `tokens`

Tokens are your own values, in groups of any depth. Each group becomes a class named after its path: `tokens.modal.border` is `AppThemeTokensModalBorder`. Each value gets a type from what is written:

| Written | Type | Read with |
|---|---|---|
| A color: `'#FF6B00'`, `'#F60'`, `'#80FF6B00'`, a `Colors` name (`white`, `black54`, `grey.shade100`, `deep-purple`), a reference to a color, or a color object `{ color: ..., alpha: 12% }` | `Color` | `tokenColor` |
| A number: `460`, `+5`, `.5`, `1e3`, `infinity` | `double` | `tokenNumber` |
| A duration: `250ms`, `250 ms`, `1.5s` (units `ms`, `s`, `m`, `h`, `d`) | `Duration` | `tokenDuration` |
| A list of colors | `List<Color>` | `tokenColors` |
| A list of numbers | `List<double>` | `tokenNumbers` |
| A list of texts | `List<String>` | `tokenTexts` |
| A map with a `source` and only image keys (`source`, `refresh`, `source-sha256`, `headers`, `timeout`, `fallback`), at least `tokens.<group>.<key>` deep | `ThemeImage` | `tokenImage` |
| Anything else | `String` | `token` |

Details that decide a type:

- A hex color has 3, 6 or 8 digits after `#`. `0xFF112233` is not a color: it is text.
- A value with a space in it is text, unless it is a number, a duration or an inset list. The old one-line form `$neon.yellow alpha 12%` is therefore a `String`; write a color object instead.
- A map with an image's `source` and any other key is a group of tokens, not an image.
- A list holds one type. `['#112233', 3]` is an error: `spring.flutter.theme.tokens.a.list[0]: a list holds one type (colors, numbers or texts), found Color, number.`

These rules are the starter's own: the generator checks every row of the starter's fixture `test/fixtures/theme_value_kinds.yaml` in a test, so the build and the running app agree on every value.

### `styles`

Each style becomes two classes: `AppStyle<Name>`, which implements `ThemeStyle` and holds the style's states, and `AppStyle<Name>Values`, with a typed getter per property for one state. Use them with the starter's `ThemeStates` widget.

```dart
// lib/spring_gen/theme.spring.keys.dart (generated), from styles.neon-chip above

/// `styles.*` of the active theme: a `ThemeStyle` per name.
final class AppThemeStyles {
  const AppThemeStyles._(this._values);
  final ThemeKeyReader _values;

  /// `styles.neon-chip`
  AppStyleNeonChip get neonChip =>
      AppStyleNeonChip._(_values.style('neon-chip'));
}

/// `styles.neon-chip`: the states and typed values.
final class AppStyleNeonChip implements ThemeStyle<AppStyleNeonChipValues> {
  const AppStyleNeonChip._(this.style);
  @override
  final StateStyle style;
  @override
  AppStyleNeonChipValues view(StyleValues values) =>
      AppStyleNeonChipValues._(values);
}

/// The values of `styles.neon-chip` for one state.
final class AppStyleNeonChipValues {
  const AppStyleNeonChipValues._(this._values);
  final StyleValues _values;

  /// `styles.neon-chip.fill`
  Color get fill => _values.color('fill');

  /// `styles.neon-chip.padding`
  EdgeInsets get padding => _values.insets('padding');

  /// `styles.neon-chip.radius`
  double get radius => _values.number('radius');
}
```

The rules:

- A property is a value, or a map of states to values. The states are `default`, `hovered`, `focused`, `pressed`, `dragged`, `selected`, `scrolled-under`, `error` and `disabled`. Another name is an error with a "did you mean": `"hoverd" is no state of a component (did you mean "hovered"?).`
- A property's type is one of `Color`, `double`, `EdgeInsets`, `String` or `Duration`, and the same in every state and every theme.
- Insets are a list of one, two or four numbers (`[all]`, `[horizontal, vertical]`, `[left, top, right, bottom]`), or a text of two or four numbers with commas. Three numbers are an error.
- `transition` belongs to the style itself, not to a state, so it gets no getter.
- A map inside a state's map is an error.

### `motion`

`motion.durations.<name>` are `Duration` getters directly on `AppThemeMotion` (`context.theme.motion.fast`); `motion.curves.<name>` are `Curve` getters on `motion.curves`. A duration is zero when the system asks for less motion: the reader is created with `MediaQuery.maybeDisableAnimationsOf(context)`. Other keys under `motion` (such as `page-transition`) get no getter. A duration named `curves` is an error, as it would clash with the `curves` getter.

```dart
// generated
final class AppThemeMotion {
  const AppThemeMotion._(this._values);
  final ThemeKeyReader _values;

  /// `motion.durations.fast`
  Duration get fast => _values.motionDuration('fast');

  /// `motion.curves.*`
  AppThemeMotionCurves get curves => AppThemeMotionCurves._(_values);
}

final class AppThemeMotionCurves {
  const AppThemeMotionCurves._(this._values);
  final ThemeKeyReader _values;

  /// `motion.curves.out`
  Curve get out => _values.motionCurve('out');
}
```

### `animations`

Each `animations.<name>` with at least one property becomes an `AnimationSpec`, for the starter's `ThemeAnimation`:

```dart
// generated
final class AppThemeAnimations {
  const AppThemeAnimations._(this._values);
  final ThemeKeyReader _values;

  /// `animations.glow-pulse`
  AnimationSpec get glowPulse => _values.animation('glow-pulse');
}
```

### `background` and `splash`

When any theme has a `background`, `AppTheme` gets `ThemeBackgroundData? get background`, which is `null` in a theme without one. When any theme has a `splash`, it gets `ThemeSplashData get splash`, which throws in a theme without one.

### Loaders and the splash

Each `loaders.<name>` gets a `ThemeLoaderSpec` getter on `context.theme.loaders`:

```dart
// lib/spring_gen/theme.spring.keys.dart of this site (generated)
final class AppThemeLoaders {
  const AppThemeLoaders._(this._values);
  final ThemeKeyReader _values;

  /// `loaders.neon-gate`
  ThemeLoaderSpec get neonGate => _values.loader('neon-gate');

  /// `loaders.spring-leaf`
  ThemeLoaderSpec get springLeaf => _values.loader('spring-leaf');
}
```

A loader of a kind of the app's own (a class with `@ThemeLoaderKind('spring-leaf')`, see [Flutter](index.md#loader-kinds-of-the-apps-own)) also gets a **props class**, `<Kind>LoaderProps`, with a getter for each key the themes give the loaders of that kind. Nested maps become nested classes. This site's own loader:

```yaml
# lib/resources/application.yml of this site, in the theme spring-dart (shortened)
loaders:
  spring-leaf:
    kind: spring-leaf
    phases:
      enter: { duration: 1400ms, curve: linear }
    background:
      color: '#04070D'
      glow: '#0E2E3A'
    leaf:
      color: $neon.green
      accent: $neon.cyan
      size: 120
      width: 2.2
      glow: 18
    # ... ring, title
    web: loaders/spring-leaf.html
```

```dart
// lib/spring_gen/theme.spring.keys.dart of this site (generated, shortened)

/// The keys of the loaders of the kind `spring-leaf`, as the
/// painter or widget of that kind reads them.
final class SpringLeafLoaderProps {
  const SpringLeafLoaderProps._(this.values);

  /// The keys of the loader, untyped.
  final LoaderValues values;

  /// The keys a loader of this kind takes besides `kind`,
  /// `phases` and `web`; `null` while no theme gives any.
  static const List<String>? keys = ['background', 'leaf', 'ring', 'title'];

  /// `loaders.*.leaf`
  SpringLeafLoaderPropsLeaf get leaf =>
      SpringLeafLoaderPropsLeaf._(values.at('leaf'));

  // ... background, ring, title
}

/// `loaders.*.leaf`
final class SpringLeafLoaderPropsLeaf {
  const SpringLeafLoaderPropsLeaf._(this._v);
  final LoaderValues _v;

  /// `loaders.*.leaf.accent`
  Color get accent => _v.color('accent');

  /// `loaders.*.leaf.color`
  Color get color => _v.color('color');

  /// `loaders.*.leaf.glow`
  double get glow => _v.number('glow');

  /// `loaders.*.leaf.size`
  double get size => _v.number('size');

  /// `loaders.*.leaf.width`
  double get width => _v.number('width');
}
```

How the props are typed:

| Written | Type |
|---|---|
| A map of `duration` with only `curve` and `repeat` besides | `AnimationSpec` |
| `true` or `false` | `bool` |
| A color, as for tokens | `Color` |
| A number | `double` |
| A duration | `Duration` |
| A text under the key `curve` | `Curve` |
| Other text, insets, an image | `String` |
| A list of colors, numbers or texts | `List<Color>`, `List<double>`, `List<String>` |

The keys `kind`, `phases`, `tracks`, `web` and `web-sha256` are read by the starter for every kind and are not props. Inside a loader's keys, a map with a `color` and other keys is a group (`door: { color: ..., edge: ... }`), not a color object, unless it has only the keys of a color object (`color`, `alpha`, `mix`).

The loader kinds the theme may name are the built-in ones (`spinner`, `dots`, `pulse`, `bar`, `skeleton`), the `@ThemeLoaderKind` classes of the package's own `lib/` (found in the source text), and the `loaderKinds` listed in the `spring_metadata.json` of each package in `dependencies`. A props class is written only for the package's own kinds.

The build fails when:

- a loader has no `kind`: `loaders.main has no kind: spinner, dots, pulse, bar, skeleton.`;
- a `kind` is unknown: `spring.flutter.theme.loaders.main.kind: unknown loader kind "doors" in loaders.main: spinner, dots, pulse, bar, skeleton (did you mean "dots"?). A kind of the app's own is a class with @ThemeLoaderKind('doors').`;
- one loader has two kinds in two themes;
- `splash.loader` names no loader of the theme: `spring.flutter.theme.splash.loader: splash.loader "spiner" is no loader.`;
- two loaders of one kind, or one loader in two themes, give different keys (with a "did you mean" for a near miss), or one key has two types.

### `AppThemes`

`AppThemes` has a `static const String` for each theme name: `light`, `dark` and `system` always, then every `themes.<name>`. Pass them to `ThemeSelection.select(AppThemes.ocean)` instead of a string.

## How a theme is read

The builder reads the themes the way the running app does, so a getter's type is the type the app will see.

1. **Layers.** The properties outside `themes` are the base. Each `themes.<name>.*` is a layer over the base, or over the theme its `extends` names. A list in a layer replaces the whole list below it. The keys `extends`, `source`, `source-sha256` and `refresh` of a layer say where a theme comes from, not how it looks, and are left out.
2. **Every theme.** Each theme (`light`, `dark` and every declared one) is resolved and checked on its own. A key's type must be the same in every theme.
3. **References.** A value `$path` takes the type of the value it points to. When the first segment of the path is not a section of the theme (`colors`, `spacing`, `tokens`, `styles`, `motion` ...), the path is a token: `$brand.accent` is `$tokens.brand.accent`. `$colors.<role>` for any Material role and `$shape.<scale>` for any name of the shape scale resolve without being declared. A reference inside a longer text must exist too, but the value stays text. `$$` is a literal `$`, and `${...}` is Spring's placeholder, so both are text.
4. **Forced types.** `colors.<name>` must be a color. `spacing.*` and `shape.*` are numbers, and `motion.durations.*` durations, whatever is written. `syntax.*` and keys named `glyphs` are always text, as they hold patterns and characters.

Because references are resolved per theme, an extending theme can change a type: if `ocean` points `$tokens.a.v` at a color while the base points it at a number, the build fails.

## Messages: `context.messages`

### The files

The message files are `<basename>.properties` and `<basename>_<locale>.properties` in `lib/resources/`, for each base in `spring.messages.basename` (comma-separated; `messages` by default; a `resources:` prefix is dropped). The builder takes the first `spring.messages.basename` it finds in the configuration files, in path order, whatever the profile.

When `spring.messages.basename` holds a placeholder (`${...}`), the build cannot know the files: it warns `spring.messages.basename has a placeholder, which the build cannot resolve: no typed messages are written.` and writes no messages file.

With several bases, a key in two bases gets one getter, from the first base.

### Getters and methods

Each key is split at its dots. Every segment but the last is a group, which becomes a class named after its path: `home.hero.title.*` is `AppMessagesHomeHeroTitle`. The last segment is the message:

| Message | Generated |
|---|---|
| No placeholder: `basket.title=Your basket` | `String get title => _context.message('basket.title');` |
| Placeholders `{0}` ... `{n}`: `basket.line={0} x {1}` | `String line(Object? arg0, Object? arg1) => _context.message('basket.line', args: [arg0, arg1]);` |

The number of parameters is the highest placeholder index plus one, so `{1}` alone gives two parameters. Placeholders inside quotes (`'{0}'`) do not count, and those in a `choice` format are counted. The doc comment of each member shows the text of the default file, so the editor shows it on hover.

### Warnings and errors

| Case | Result |
|---|---|
| A key in the default file is missing in a locale file | Warning: `lib/resources/messages_ja.properties: basket.line is missing (it is in messages.properties).` |
| A key is only in locale files | Warning: `lib/resources/messages_ja.properties: order.note is not in messages.properties.` |
| A key has a different number of arguments in two files | Error: `lib/resources/messages_ja.properties: order.sum has 2 argument(s), messages.properties has 1: the typed message needs the same number in every language.` |
| A placeholder `MessageFormat` rejects (a bad index, an unknown format type, unmatched braces) | Error: `lib/resources/messages.properties: bad.key: Invalid argument index 'x' in "Oops {x}".` |
| A key is a message and the prefix of other keys | Error: `Message key basket.total: basket is a message and also the prefix of other keys.` |
| A segment cannot be a Dart name | Error: `Message key nav.docs/api: "docs/api" cannot be written as a Dart name (letters, digits, - and _ only).` |
| Two keys become one Dart name (`order.total-sum` and `order.total_sum`) | Error: `Message keys ... and ... both become 'totalSum': rename one.` |
| Two groups become one class name (`a.bC` and `a.b.c`) | Error naming both prefixes. |
| A message file does not parse | Error with the file and the parser's message. |

A missing message is only a warning because the app still works: the message source falls back to the default file.

## Names

The keys of the configuration become Dart names by fixed rules:

| Rule | Key | Dart name |
|---|---|---|
| `-` and `_` start a new word | `surface-container-low`, `neon_night` | `surfaceContainerLow`, `neonNight` |
| The first letter becomes lower case; the rest is kept | `NotBlank`, `loginToOrder` | `notBlank`, `loginToOrder` |
| A leading digit gets a `$` before it | `2xl` | `$2xl` |
| A Dart keyword, or a member every object has, gets a `$` after it | `default`, `hashCode` | `default$`, `hashCode$` |
| Any other character (a space, `/`, a letter outside `A-Z a-z`) | `a b` | none: an error |

Classes are named from the same names with the first letter in upper case: `AppThemeTokens` + `Modal` + `Border`, `AppStyle` + `NeonChip`, `AppMessages` + `Basket`, `SpringLeaf` + `LoaderProps`.

Keys are compared as the runtime compares them: in lower case, without `-` and `_`. `surface-container-low` and `surfaceContainerLow` are one key, written the way it is first seen.

Two keys that become one Dart name, or two paths that become one class name, are an error that names both (`... both become the class AppThemeTokensModal: rename one.`). A generated class may also not take a name the files use from Flutter or the starter, such as `TextStyle`, `Color`, `ThemeStyle` or `LoaderValues`.

## Theme errors

Besides the errors of each section above, the build fails for:

| Problem | Message |
|---|---|
| An unknown reference | `spring.flutter.theme.tokens.a.x: unknown reference $colors.brand-acent (tokens.a.x -> $colors.brand-acent). Did you mean $colors.brand-accent?` |
| References in a cycle | `References form a cycle: ... -> ...` |
| A reference to a group | `...: $tokens.modal is a group of values, not a value (...).` |
| A token with two types in two themes | `tokens.a.v has values of different types: number in spring.flutter.theme.tokens.a.v; Color in spring.flutter.theme.themes.ocean.tokens.a.v. Use one type in every theme.` |
| A token that is a group in one theme and a value in another | `tokens.b.c is a group of tokens in some themes and a value in others.` |
| A wrong color object (an unknown key, no `color`, a bad `mix` or percent) | `...: a color object with a 'color' is expected.`, `...: a percent: 0% to 100% or 0 to 1.` |
| An `extends` that names no theme, or a cycle of `extends` | `Theme 'ocean' extends 'neno', which is no theme` |

An error found in several themes is reported once. A message found in a theme other than `light` ends with the theme's name: `(theme 'ocean')`.

## When something is wrong

Warnings go to the build log, and the files are written. Errors also go to the build log, fail the build, and **neither** file is written. Because both are declared outputs, `build_runner` removes the files the step did not write, and code that uses `context.theme` stops compiling until the configuration is fixed. All errors are listed together, so one build shows every problem.

## In Spring (Java)

Spring has no counterpart. A Java application reads message keys by string (`messageSource.getMessage("basket.total", ...)`), and Spring has no theme configuration.

## See also

- [Flutter](index.md)
- [The page loader](page-loader.md), which reads the same theme for the web page
- [Metadata for editors](../metadata.md)
- [Messages](../../spring-core-dart/messages/index.md)
- [Profiles](../../spring-core-dart/config/profiles.md)
