State beans
In Flutter, shared state is usually a ChangeNotifier whose methods end with notifyListeners(); a forgotten call leaves the screen stale. Here the bean's generated proxy (an object that wraps the bean and runs code around its methods) makes that call. Two annotations do it:
@ChangeNotifierComponent()for a plain class: noextends ChangeNotifier, nonotifyListeners().@NotifyListeners()for a class that already extendsChangeNotifier.
Why
State in beans can be shared by every screen and every service: the basket the book screen fills is the one the badge counts and the checkout reads. With the notification generated, a method cannot forget it, and a widget rebuilds only when it shows the state, not when it merely calls a method.
@ChangeNotifierComponent
It declares a state bean from a plain class. It is a @Component, so the class becomes a bean. Its proxy is a ChangeNotifier and notifies after every public method and setter, except the ones named in exclude. Getters never notify.
// The basket, shared by the book screen, the badge and the Basket screen.
@ChangeNotifierComponent(exclude: ['peek'])
class Basket {
Basket(this._api);
final ShopApi _api;
final _items = <String>[];
int get count => _items.length; // a getter: never notifies
void add(String isbn) => _items.add(isbn);
void clear() => _items.clear();
String? peek() => _items.lastOrNull; // excluded: only reads
Future<void> load() async { // notifies when the Future completes
_items.addAll(await _api.basket());
}
}
The class itself is no Listenable, since generated code cannot give it a superclass; the bean the container hands out is. So:
SpringStatelessWidgetandSpringStatesubscribe to it by themselves;- elsewhere,
listenableOf(bean)gives theListenable:ListenableBuilder(listenable: listenableOf(context.basket), builder: ...). It throws anArgumentErrorfor an object that is noListenable, such as an instance created by hand.
The build fails when a name in exclude is not a method, setter or field of the class, or when the class declares one of ChangeNotifier's own members (addListener, dispose, ...).
@NotifyListeners
It does the same for a class that already extends ChangeNotifier, for example because it also notifies from a stream callback. On the class it notifies after every public method and setter (except exclude); on a method or setter, after that one only.
// Notifies after `select`, `clear` and every write to `selected`.
@Component()
@NotifyListeners()
class Search extends ChangeNotifier {
Book? selected;
void select(Book book) => selected = book;
void clear() => selected = null;
}
// Only `restock` notifies.
@Component()
class Stock extends ChangeNotifier {
final _available = <String, int>{};
@NotifyListeners()
void restock(String isbn, int count) => _available[isbn] = count;
}
When listeners are notified
- After the method returns, also when it throws (the state may have changed before the error).
- After a returned
Futurecompletes. - On the bean the container hands out, not on an instance created by hand.
- Calls the bean makes on itself (
this.add(...)) notify only when its proxy is a subclass proxy (a class with private members); otherwise only calls from outside notify.
Reading is free
A Spring widget listens to a @ChangeNotifierComponent bean, or to a class marked @NotifyListeners, only when its build read the bean's state: a getter or a field. Calling a method (onPressed: counter.increment) costs no rebuilds. So a page can hold the counter for its button while only the Text that shows the count rebuilds:
class CounterPage extends SpringStatelessWidget<(Counter,)> {
const CounterPage({super.key});
@override
Widget build(BuildContext context) {
final (counter,) = beans;
return Scaffold(
body: const CounterText(), // rebuilt after a tap
floatingActionButton: FloatingActionButton( // the page is not
onPressed: counter.increment,
child: const Icon(Icons.add),
),
);
}
}
The proxy sees the reads, so the rule follows what the widget actually shows: a build that stops reading the bean stops listening, and the next one that reads it listens again. The bean's reads of itself, inside its own methods, do not count.
One case to know: a read outside the widget's own build (in a ListView.builder item builder, a Builder below it, a callback, initState, another bean) cannot be told apart from a read for the screen. After one, every widget holding the bean keeps listening, so the screen is never stale but may rebuild more than needed. Call methods rather than reading state outside build when that matters.
Any other Listenable bean (a plain ChangeNotifier, or one with @NotifyListeners on methods only) is listened to always.
In Spring (Java)
Spring has no counterpart. It is advice around the bean's methods, like @Transactional: the proxy runs code after each call.
See also
- Beans in widgets
- Signals beside ChangeNotifier: state followed by field,
@Signal,@Computed,@Effect - Bloc and Cubit: state in blocs that are beans
- AOP in spring_core_dart
- The generator for Flutter