Fields and computed values
@Signal() marks a field whose changes are followed: what read it (a widget's build, a @Computed value, an @Effect method) is told when it is assigned. @Computed() marks a value made from other state, kept until what it read changes.
Why
The state of a screen is a few fields and the values made from them. Written by hand, each value needs to know when to be computed again, and each reader needs to know when to look again. Here both follow from what was read.
Example
@Component()
class Basket {
Basket(this.storage); // ordinary injection
final BasketStorage storage;
@Signal()
List<Book> items = [];
@Signal()
String? coupon;
@Computed() // kept until items or coupon changes
double get total =>
items.fold(0.0, (sum, book) => sum + book.price) *
(coupon == null ? 1 : 0.9);
void add(Book book) => items.add(book);
void apply(String code) => coupon = code;
}
Where the annotations go
The annotations are for the members of a component: a class the container makes (@Component, @Service, ...). They are not for the members of a @Configuration class.
The members must be public: the proxy is generated in another library, and a private member cannot be overridden from there. The build fails otherwise, naming the member (see What the build checks).
@Signal
| On | Rule |
|---|---|
| A field of a component | Public, not static, not final |
- The field stays a plain field: no wrapper type and no
.value. - A change is an assignment. For a
List, aSet, aMapor aQueuea change in place is one too (see Collections). - Assigning a value equal to the one there tells nobody.
- A field nobody read is not followed yet: it is mirrored when first read, from the field itself.
@Signal(hidden: true)keeps the value out of the debug tab and of the log (see The debug tab and the log).
@Computed
| On | Rule |
|---|---|
| A getter, or a method without parameters, of a component | Public, not static, with a value |
@Computed()
bool isEmpty() => items.isEmpty;
- It is computed when first read, and again only after a
@Signalfield or another computed value it read has changed. - Read again without a change, it gives the same value and is not computed again.
- A getter that returns a
Futureor aStreamis asynchronous state: see Asynchronous state.