grabAt<S> method
Returns an object chosen with the selector
, and starts listening
for changes in the ValueListenable to rebuild the widget associated
with the provided BuildContext when there is a change in the
selected object.
The callback of the selector
receives the value
of the
ValueListenable
that this method was called on.
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 Item extends ChangeNotifier {
Item({required this.name, required this.quantity});
final String name;
final int quantity;
}
final notifier = ValueNotifier(
Item(name: 'Milk', quantity: 3),
};
...
class InventoryItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final name = notifier.grabAt(context, (item) => item.name);
return Text(name);
}
}
The object to select can be anything as long as it is possible to
evaluate its equality with the previous object using the ==
operator.
final hasEnough = notifier.grabAt(context, (item) => item.quantity > 5);
Supposing that the quantity was 3 in the previous build and has changed to 2 now, the widget is not rebuilt because the value returned by the selector has remained false.
Implementation
S grabAt<S>(BuildContext context, GrabSelector<R, S> selector) {
if (Grab.stateOf(context) case final grabState?) {
return grabState.listen(
context: context,
listenable: this,
selector: selector,
);
}
throw GrabMissingError();
}