Flutter

For an app on spring_boot_starter_flutter, the generator writes the code that connects widgets to the application context. Widgets are not beans: Flutter creates them with their own constructors, so nothing can inject into them. The generated code fills that gap, at build time, from annotations and types that the generator reads in your code.

The generator does not depend on the Flutter starter. It recognises the starter's annotations and classes by their URL (for example package:spring_boot_starter_flutter/src/annotations.dart#BuildContextAccess), the same way it recognises the annotations of the other starters. A module that uses none of them gets nothing Flutter-specific in its .spring.dart file.

Why

Widget code needs beans: a basket, a session, the current language. Without generated code, a widget looks each bean up by type at run time (context.bean<Basket>()). That works, but:

The generator moves this work to the build. It writes typed getters for beans, fills the bean records of widgets, lets the app check at startup that every bean a widget needs exists, and writes proxies that notify listeners for you.

What it recognises

In your code What the build writes Where
@BuildContextAccess() on a bean class or @Bean method A getter in extension SpringBeans on BuildContext The module's .spring.dart
A class that extends SpringStatelessWidget<R>, or a State that extends SpringState<W, R> A binding in the module's SpringWidgetBindings bean The module's bean list
@ChangeNotifierComponent() or @NotifyListeners() A proxy class that notifies listeners (and mixes ChangeNotifier in, for the first) The module's .spring.dart
@ThemeLoaderKind('name') on a loader class A registration into ThemeLoaderKinds The module's getter
@ScreenRoute(...) and @RouteShell(...) widgets (spring_boot_starter_flutter_navigation) A ScreenRoutes bean and one route extension per screen The module's .spring.dart
spring.flutter.theme.* and messages*.properties context.theme and context.messages lib/spring_gen/theme.spring.keys.dart, lib/spring_gen/messages.spring.keys.dart

The module is the @SpringBootApplication or @ComponentScan library; its .spring.dart file is the one the main builder writes next to it in spring_gen/, such as lib/spring_gen/main.spring.dart. Widgets import that file to use the getters and extensions.

The code excerpts below come from real generated files. Import prefixes such as _i10. are dropped to make them easier to read.

@BuildContextAccess: a getter per bean

Put @BuildContextAccess() on a bean, and every widget below SpringApplicationWidget can reach it as context.<name>.

// lib/src/basket/basket.dart
@ChangeNotifierComponent()
@BuildContextAccess()
class Basket {
  Basket(this._shop);
  // ...
}

The build writes one extension per module, with a getter per marked bean:

// lib/spring_gen/main.spring.dart (generated)

/// Getters for the `@BuildContextAccess` beans, for widgets below `SpringApplicationWidget`.
extension SpringBeans on BuildContext {
  /// The bean 'session'.
  Session get session =>
      SpringScope.beanOf<Session>(this, qualifier: r'session');

  // ...

  /// The bean 'basket'.
  Basket get basket =>
      SpringScope.beanOf<Basket>(this, qualifier: r'basket');
}
// In a widget:
Text('${context.basket.count}');

How the getter is made:

  1. Its name is the bean's name (basket for the class Basket), or the name you give: @BuildContextAccess(name: 'cart').
  2. Its type is the type the bean is known by: the class for a class bean, the declared return type for a @Bean method (the type inferred from the method's body may be a private or narrower class), the product type for a FactoryBean.
  3. Its body looks the bean up with SpringScope.beanOf<T>(this, qualifier: '<bean name>'). The bean name is the qualifier, so the getter finds this exact bean even when other beans share its type.

@BuildContextAccess may stand on the class or on the @Bean method that creates the bean.

Errors

The build collects every invalid getter of a module and reports them together. Each error names the bean and its source, and ends with the fix.

Problem Example message
The name is no Dart identifier @BuildContextAccess(name: 'my-cart') on ...: 'my-cart' is not a valid Dart identifier for a getter. Choose another name.
The name is private ...: '_cart' is private, so widgets could not use the getter.
The name is a reserved word @BuildContextAccess on bean 'default' (...): 'default' is a reserved word. Give the getter a name: @BuildContextAccess(name: 'myGetter').
The name is a member of BuildContext, Object or the starter's SpringBuildContext ...: 'size' clashes with BuildContext.size, which a generated getter cannot replace.
Two beans get the same getter ...: the getter 'cart' is already generated for bean 'cart' (...). Give one of them another name with @BuildContextAccess(name: '...').
The class is no bean @BuildContextAccess on Basket, which is no bean of this application: add @Component() (or another stereotype), or put @BuildContextAccess on the @Bean method that creates it.

The members that a getter cannot take are those of BuildContext (widget, owner, mounted, size, findRenderObject, the dependOn..., find..., visit... and describe... methods, ...), of Object (hashCode, runtimeType, toString, noSuchMethod) and of SpringBuildContext (springContext, bean, message). An extension getter with such a name would be hidden by the real member, so the build refuses it.

Widgets with beans

A widget names the beans it needs in a record type, and reads them from beans in build:

// lib/src/basket/basket_badge.dart
class BasketBadge extends SpringStatelessWidget<(Basket,)> {
  const BasketBadge({super.key});

  @override
  Widget build(BuildContext context) {
    final (basket,) = beans;
    final count = basket.count; // read in build: the badge rebuilds when the basket notifies
    return Badge(
      isLabelVisible: count > 0,
      label: Text('$count'),
      child: const Icon(Icons.shopping_basket_outlined),
    );
  }
}

// With more beans, a typedef keeps the class line short.
typedef SettingsPageBeans = (
  ThemeSelection,
  SpringThemes,
  LanguageSelection,
  AppAssets,
);

class SettingsPage extends SpringStatelessWidget<SettingsPageBeans> { ... }

// A stateful widget: the State gets the beans.
class _CatalogPageState extends SpringState<CatalogPage, (Catalog,)> { ... }

Filling a record needs code that names each field, and Dart has no reflection to do it at run time. So the build writes a binding for each record type. All bindings of a module go into one bean, SpringWidgetBindings:

// lib/spring_gen/main.spring.dart (generated), in the module's bean list
BeanDefinition<SpringWidgetBindings>(
  name: r'flutterSpringWidgetBindings#application',
  source: r'package:spring_boot_starter_flutter/spring_boot_starter_flutter.dart#SpringWidgetBindings',
  autowireCandidate: false,
  create: (r) => SpringWidgetBindings([
    SpringWidgetBinding(
      widget: r'package:neon_books_app/src/settings/settings_page.dart#SettingsPage',
      beans: SettingsPageBeans,
      types: const [ThemeSelection, SpringThemes, LanguageSelection, AppAssets],
      resolve: (f) => (
        SpringWidgetBinding.bean<ThemeSelection>(f),
        SpringWidgetBinding.bean<SpringThemes>(f),
        SpringWidgetBinding.bean<LanguageSelection>(f),
        SpringWidgetBinding.bean<AppAssets>(f),
      ),
      values: (r) {
        final v = (r as (ThemeSelection, SpringThemes, LanguageSelection, AppAssets));
        return [v.$1, v.$2, v.$3, v.$4];
      },
    ),
    // ... one binding per record type
  ]),
),

What each part does:

Field Role
widget The class that declared the record, package:<app>/<file>.dart#<Class>, for error messages.
beans The record type as a Type value. Widgets find their binding by this type. A record written inline, such as (Basket,), is written through a generated _$typeOf<(Basket,)>() helper, as a record type cannot be written as a plain type literal.
types The bean types that must exist: those of the non-nullable fields. SpringApplicationWidget checks them at startup.
resolve Fills the record from the bean factory.
values Lists the beans of a filled record, so the widget can listen to the ones that are Listenable.

The bean is named flutterSpringWidgetBindings#<module> and is no autowire candidate: no bean can receive it by injection. The starter finds it with getBeansOfType.

How each field is filled

Field in the record Generated call At run time
Positional, non-nullable: (Basket,) SpringWidgetBinding.bean<Basket>(f) The bean of that type. Fails when there is none, or several and none is primary.
Named, non-nullable: ({Clock clock}) SpringWidgetBinding.bean<Clock>(f, 'clock') The bean of that type; when several beans have it and none is primary, the one whose name is the field's name.
Nullable: (Basket?,) f.findBean<Basket>() The bean, or null. Not checked at startup.

One binding per record type

Widgets find their binding by record type, so two widgets with the same record share one binding: the build writes it once, under the name of the first widget it scanned. BasketBadge and another widget that both declare (Basket,) use the same code.

The check at startup

After the context starts, SpringApplicationWidget goes through every binding and checks that a bean exists for each type in types. A missing bean stops the start with a NoSuchBeanDefinitionException that names the widget, instead of failing later when the widget first builds.

If a widget's record has no binding at run time (the generator did not run after the widget was written), the first build throws a FlutterError: No generated beans for BasketBadge ((Basket,))., with the hint to run dart run build_runner build, and that a hot restart may be needed after changing a record type.

Errors

Problem Message
The type argument is not a record, or is a nullable record SpringStatelessWidget BasketBadge: its beans must be a record of bean types, like SpringStatelessWidget<(Basket, AppNavigator)>, not Basket.
A field is not a class or interface type (dynamic, Object, Function, Null, a record, a function type) SpringStatelessWidget BasketBadge: Object (positional field of (Object,)) is not a bean type; every field of the record must be a class or interface type (nullable for an optional bean).

An abstract class whose record is still a type parameter (a base class such as abstract class MyBase<R extends Record> extends SpringStatelessWidget<R>) is skipped: its concrete subclasses get the bindings. A concrete class whose record is a type parameter fails with the first error.

@ChangeNotifierComponent and @NotifyListeners

A state bean must tell its widgets when it changes. The starter's two annotations ask the generated proxy to do it:

Getters never notify. For a method that returns a Future, listeners are notified when the future completes. They are notified also when the method throws.

The proxy for the Basket above (a class with private members, so the proxy is a subclass):

// lib/spring_gen/main.spring.dart (generated)
/// Basket: `@ChangeNotifierComponent()`
class _$BasketProxy extends Basket with ChangeNotifier, AdvisedSubclass {
  _$BasketProxy(super.p0);

  /// add: `@ChangeNotifierComponent()`
  @override
  Future<void> add(Book book) {
    final _$invoker = this.aopInvoker;
    return _$invoker == null
        ? super.add(book)
        : _$invoker.invokeAsync<void>(
            proxy: this,
            target: this,
            methodIndex: 0,
            arguments: [book],
            original: (args) => super.add((args[0] as Book)),
          );
  }
  // ... every other member
}

The notifying itself is advice, as for @Transactional. The starter registers two advisors whose pointcuts match the two annotations, and the proxy sends each call through them:

That is why the proxy overrides the getters too. The bean the container hands out is a Listenable, even though the class Basket is not one to the compiler. Spring widgets subscribe to it by themselves; elsewhere, listenableOf(bean) gives it the Listenable type.

These proxies are always generated. When the build prunes AOP proxies, it never removes or defers the proxy of a @ChangeNotifierComponent class: without it, the bean would be no ChangeNotifier at all. A bean with @NotifyListeners keeps its proxy because the starter's pointcuts declare the annotations they match (static const annotationTypes), so the build knows they apply.

Errors

Problem Message
A name in exclude is no public method, setter or field of the class (its own or inherited) @ChangeNotifierComponent on Counter: exclude names rest, which is no public method, setter or field of Counter.
A @ChangeNotifierComponent class that is not a ChangeNotifier declares addListener, removeListener, dispose, notifyListeners or hasListeners @ChangeNotifierComponent on Counter: dispose would clash with the ChangeNotifier its proxy mixes in; rename it, or let Counter extend ChangeNotifier.

Without the first check, a typo in exclude would silently exclude nothing.

Loader kinds of the app's own

A theme names its loaders by kind: spinner, dots, pulse, bar, skeleton are built in. A class marked @ThemeLoaderKind('doors') that extends ThemeLoaderPainter<P> or ThemeLoaderWidget<P> adds a kind. The module registers it in its getter, before the module is built, so the themes find the kind when they are read:

// lib/spring_gen/main.spring.dart (generated)
BeanModule get $application {
  ThemeLoaderKinds.register<SpringLeafLoaderProps>(
    r'spring-leaf',
    widget: SpringLeafLoader(),
    props: SpringLeafLoaderProps._,
    keys: SpringLeafLoaderProps.keys,
  );
  return BeanModule(r'application', [/* the beans */]);
}

SpringLeafLoader is a ThemeLoaderWidget, so it is passed as widget:; a ThemeLoaderPainter is passed as painter:. The props class SpringLeafLoaderProps is written by the typed keys builder from the keys the themes give the loaders of that kind; see Typed keys. When the class takes LoaderValues instead of the generated props class, the registration has no props: and keys:.

The build fails when:

Screens and routes

With spring_boot_starter_flutter_navigation, a widget marked @ScreenRoute('/path') is a screen, and one marked @RouteShell(branches: [...]) is a shell with a stack per branch. The build collects them into one ScreenRoutes bean per module, written with the same builder an app would use by hand:

// Input
@ScreenRoute('/components/{*path}', title: '#{docs.title}', content: 'resources:content/components/')
class DocsPage extends StatelessWidget {
  const DocsPage({super.key});
  // ...
}
// lib/spring_gen/main.spring.dart (generated), in the module's bean list
BeanDefinition<ScreenRoutes>(
  name: r'screenRoutes#application',
  source: r'package:spring_boot_starter_flutter_navigation/spring_boot_starter_flutter_navigation.dart#ScreenRoutes',
  create: (r) => ScreenRoutes.route(source: r'application')
      .screen(
        r'/components/{*path}',
        (r) => const DocsPage(),
        name: r'docs-page',
        title: r'#{docs.title}',
        content: r'resources:content/components/',
        source: r'package:neon_farum_azula/src/pages/docs/docs_page.dart#DocsPage',
      )
      // ... the other screens
      .notFound((r) => const NotFoundPage())
      .build(),
),

Each screen, except the not-found screen, also gets an extension with its constants and a typed to(...):

// lib/spring_gen/main.spring.dart (generated)

/// The route of [DocsPage]: its path, name, values and `to`.
extension DocsPageRoute on DocsPage {
  /// The path pattern.
  static const pattern = r'/components/{*path}';

  /// The route's name.
  static const routeName = r'docs-page';

  /// The path variable `path`.
  static const path = RouteVar<String>(r'path');

  /// The location of this screen with these values.
  static RouteLocation to({required String path}) =>
      RouteLocation.expand(pattern, pathVariables: {r'path': path});
}

The extension has a RouteVar<String> per path variable, a RouteParam<T> per query parameter declared with params: {'page': int}, a RouteExtra<T> for extra:, and to(...) with a required String per path variable and an optional value per parameter. A renamed path, variable or parameter breaks the code that uses it, at compile time.

The rules the build applies:

The build fails when a class with @ScreenRoute or @RouteShell is no widget, or has both; when a screen has no unnamed constructor without required parameters (the router creates it; it reads its values from context.route); when a shell's unnamed constructor does not take its ShellState as its only required parameter, it declares no branch, or a branch is not a path starting with / without variables; when a path does not start with /, has unbalanced braces, a {*rest} before its end, or a variable twice; when a query parameter has the name of a path variable; and when two screens of a module declare one path, or two are the not-found screen.

The screens and shells are also listed in spring_metadata.json (routes, shells): see Metadata for editors.

The Flutter builders

Besides the main builder, five builders serve Flutter apps. Each one writes nothing for a package that does not use what it reads, and each has its own page:

Builder Writes Page
spring_flutter_keys lib/spring_gen/theme.spring.keys.dart, lib/spring_gen/messages.spring.keys.dart Typed keys
spring_flutter_web web_dev_config.yaml The web dev server
spring_flutter_page_loader A block in web/index.html The page loader
spring_flutter_seo A page per route and Markdown file in web/, sitemap.xml, robots.txt, llms.txt Pages for search engines
spring_flutter_deep_links Blocks in Info.plist, Runner.entitlements, AndroidManifest.xml; apple-app-site-association, assetlinks.json Deep links

The properties these builders read at build time are listed in Properties the build reads.

In Spring (Java)

Spring has no counterpart: it has no UI toolkit whose objects are created outside the container. @ChangeNotifierComponent and @NotifyListeners follow Spring's model of advice around a bean's methods, as @Transactional does.

See also