In widgets

A widget is built again for the state its build read, and for nothing else. A Spring widget follows its own build; an ordinary widget uses Watch; AsyncView shows an asynchronous value.

Why

With one notification for a whole bean, every widget that listens to the basket is built again when anything of the basket changes. Here a badge that shows the total is built again when the total changes, and a label that shows the coupon when the coupon does.

Example

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

  @override
  Widget build(BuildContext context) {
    final (basket,) = beans;
    return Text('${basket.total}');   // built again when the total changes
  }
}

Spring widgets

A SpringStatelessWidget and a SpringState follow their own build, by field. The badge above is built again when total changes and not when anything else of the basket does. Calling a method (onPressed: basket.clear) reads nothing and costs no rebuild.

See Beans in widgets for the Spring widgets.

Watch

An ordinary widget uses Watch, which is also the way to keep a rebuild small inside a large build:

Watch((context) => Text('${context.bean<Basket>().total}'))

It builds again when followed state its builder read has changed, and only then. Two assignments in one method are one build. A Watch that left the screen is not built again.

AsyncView

AsyncView shows an asynchronous @Computed value: its data, the load, or the failure.

AsyncView(
  () => context.bean<Catalog>().books,
  loading: (context) => const Spinner(),
  data: (context, books) => BookList(books),
)

The value is read inside the view (hence the function), so the view is built again by itself when the load moves on and when the future changes. The widget around it is not built again.

Parameter Type Meaning
value (positional) Future<T> Function() Gives the future; AsyncView.stream takes Stream<T> Function() and shows the stream's last event
data Widget Function(BuildContext, T) Builds the value; required
loading WidgetBuilder? Builds the first load; nothing by default
error Widget Function(BuildContext, Object, StackTrace?)? Builds a failure; its text by default

While a value is asked for again with refresh() the last one stays on screen.

AsyncView.stream(
  () => catalog.price,
  data: (context, price) => Text('$price'),
)

See also