grab<R extends Listenable> method
Returns the Listenable itself that this method was called on,
and starts listening for changes in the Listenable
to rebuild
the widget associated with the provided BuildContext when
there is a change.
A Grab is necessary as an ancestor of the widget this method is used for. GrabMissingError is thrown otherwise.
void main() {
runApp(
const Grab(child: ...),
);
}
class ItemNotifier extends ChangeNotifier {
ItemNotifier({required this.name, required this.quantity});
final String name;
final int quantity;
}
final notifier = ItemNotifier(name: 'Milk', quantity: 3);
...
class InventoryItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final n = notifier.grab<ItemNotifier>(context);
return Text(n.name);
}
}
In the above example, grab()
returns the ItemNotifier itself.
Therefore it is not much different from the code below:
@override
Widget build(BuildContext context) {
notifier.grab<ItemNotifier>(context);
return Text(notifier.name);
}
Note that specifying a wrong Listenable type causes an error only at runtime.
Implementation
R grab<R extends Listenable>(BuildContext context) {
return grabAt<R, R>(context, (listenable) => listenable);
}