Beans per screen or branch
Two bean scopes follow the navigation. A route bean is created when its screen opens and destroyed when it closes, after its exit animation. A branch bean is created on the first visit of its branch and destroyed when the shell closes (leaving the tabs, a logout).
Why
A form's state belongs to its screen: it should be fresh each time the screen opens, and gone when it closes. A tab's state (a search, a filter) belongs to the tab. As singletons they leak from one visit to the next; as State fields they cannot be shared with services. Scoped beans are both: injected like any bean, and as short-lived as the screen or the tab.
Example
// A fresh form each time the book's edit screen opens.
@ChangeNotifierComponent()
@Scope(NavigationScopes.route)
class BookForm {
String title = '';
void rename(String value) => title = value;
}
// The catalog tab's search, kept while the user switches tabs.
@ChangeNotifierComponent()
@Scope(NavigationScopes.branch)
class CatalogSearch {
String query = '';
void search(String value) => query = value;
}
@ScreenRoute('/catalog/books/{isbn}/edit')
class EditBookPage extends SpringStatelessWidget<(BookForm,)> {
const EditBookPage({super.key});
@override
Widget build(BuildContext context) {
final (form,) = beans; // this screen's own form
return TextField(onChanged: form.rename);
}
}
The scopes
| Scope | Created | Destroyed |
|---|---|---|
NavigationScopes.route ('route') |
When its screen opens | When the screen closes, after its exit animation |
NavigationScopes.branch ('branch') |
On the first visit of its branch | When the shell closes |
A lookup from a widget gets the beans of that widget's screen and branch: two screens of the same route on the stack each have their own. Any other lookup (a singleton, a service) gets those of the screen on top. The starter does it with a BeanLookupScope around every screen.
In Spring (Java)
Spring Web has request and session scopes; these are the same idea for screens and tabs.