Beans in widgets

Services get their beans through their constructors. Widgets cannot: Flutter and your own code create them, so nothing is injected into them. A widget gets beans in one of four ways:

Way Typed Checked at the start Rebuilds on change Use it for
SpringStatelessWidget<(...)> yes yes yes Most widgets that show or use beans
SpringStatefulWidget<(...)> with SpringState yes yes yes The same, with a State (controllers, initState)
context.bean<T>() yes no no One-off uses: a button that calls a service
context.basket (@BuildContextAccess) yes yes no The few beans many widgets need deep in the tree

Why

Passing services through constructors from the root to the leaves is tedious, and a Provider tree must be kept in step with the services by hand. Here the widget names what it needs in its type, the generator sees it, and a missing bean fails the start, not some later build in front of a user.

SpringStatelessWidget

The widget lists its beans in its type, as a record, and reads them from beans in build:

// The basket's icon with the number of books.
class BasketBadge extends SpringStatelessWidget<(Basket,)> {
  const BasketBadge({super.key});

  @override
  Widget build(BuildContext context) {
    final (basket,) = beans;
    return Badge(
      label: Text('${basket.count}'),
      child: const Icon(Icons.shopping_basket_outlined),
    );
  }
}

Compared with context.bean:

For several beans, name the record with a typedef named after the widget, one bean per line with a trailing comma:

/// The beans of [BasketBadge].
typedef BasketBadgeBeans = (
  Basket,
  Clock,
);

class BasketBadge extends SpringStatelessWidget<BasketBadgeBeans> {
  const BasketBadge({super.key});

  @override
  Widget build(BuildContext context) {
    final (
      basket,
      clock,
    ) = beans;
    return Badge(
      label: Text('${basket.count}'),
      isLabelVisible: clock.now().hour < 22, // no badge at night
      child: const Icon(Icons.shopping_basket_outlined),
    );
  }
}

Rules:

SpringStatefulWidget and SpringState

The same for a widget that also needs a State: a text controller, an animation, or work started in initState. The State has the beans as beans, available from initState on. Dart cannot take the record from the widget, so it is written on both; the compiler checks that they match, and a typedef keeps it in one place.

/// The beans of [BasketPage].
typedef BasketPageBeans = (
  Basket,
  Clock,
);

class BasketPage extends SpringStatefulWidget<BasketPageBeans> {
  const BasketPage({super.key});

  @override
  State<BasketPage> createState() => _BasketPageState();
}

class _BasketPageState extends SpringState<BasketPage, BasketPageBeans> {
  @override
  void initState() {
    super.initState();
    // Fetch the basket from the server once, when the page opens.
    final (
      basket,
      _,
    ) = beans;
    basket.load();
  }

  @override
  Widget build(BuildContext context) {
    final (
      basket,
      clock,
    ) = beans;
    return Text('${basket.count} books at ${clock.now()}');
  }
}

A SpringState that overrides dispose or didChangeDependencies must call super.

context.bean

context.bean<T>() returns any bean by type, or by name with qualifier:. It works in every widget and callback, so it suits one-off uses. It does not rebuild the widget when the bean changes.

// Sends the order when tapped.
FilledButton(
  onPressed: () => context.bean<OrderService>().placeOrder(),
  child: const Text('Order'),
);

// A bean by name.
final mail = context.bean<MailSender>(qualifier: 'transactional');

Generated getters: @BuildContextAccess

Mark a bean @BuildContextAccess() and the generator writes a typed getter on BuildContext, named after the bean: context.basket. Use it for the few beans many widgets need, deep in the tree: a basket, a session, the current user. Only marked beans get one, so the list stays short. @BuildContextAccess(name: 'cart') picks another name.

@ChangeNotifierComponent()
@BuildContextAccess()
class Basket { ... }

// In a book's tile: put the book into the basket on a tap.
IconButton(
  onPressed: () => context.basket.add(book),
  icon: const Icon(Icons.add_shopping_cart),
);

The getters are generated into spring_gen/main.spring.dart; import it where you use them. Like context.bean, a getter does not rebuild the widget when the bean changes.

When Spring widgets rebuild

A SpringStatelessWidget or SpringState rebuilds when one of its beans that is a Listenable notifies. For a @ChangeNotifierComponent or @NotifyListeners bean, only when the widget's build read its state (see Reading is free). Every widget that gets beans is also built afresh when the context is replaced after a hot reload.

With context.bean and the getters, listen yourself, as usual in Flutter: ListenableBuilder for a Listenable (listenableOf(bean) gives it for a state bean), StreamBuilder for a stream.

Building with fakes

A SpringStatelessWidget can be built with fakes and no application, through buildWith:

final widget = const BasketBadge().buildWith(context, (FakeBasket(), FakeClock()));

Scopes of lookups

BeanLookupScope runs the bean lookups of the widgets below it (context.bean<T>(), the generated getters, the records of Spring widgets) in its zone, so a custom bean scope knows which part of the app asks. The navigation starter puts one around every screen for its route and branch scopes.

Known limits

In Spring (Java)

Spring has no counterpart: a Java bean is injected into a controller or a view, never looked up from a UI tree. The record of beans plays the role of a constructor's parameters.

See also