callAfterEveryBuild function
Executes a callback after every frame has been rendered. This is useful when you need to perform operations after each rebuild that require the widget tree to be fully built and laid out, such as:
- Updating scroll positions after content changes
- Repositioning overlays or tooltips
- Performing measurements that need to run after every layout
The callback is called after every build/rebuild of the widget. The cancel
function can be called from within the callback to stop future invocations.
Important: This function must be called in the same order on every build, following watch_it's ordering rules.
Example usage:
class ChatWidget extends WatchingWidget {
final scrollController = ScrollController();
@override
Widget build(BuildContext context) {
final messages = watchValue((ChatModel m) => m.messages);
callAfterEveryBuild((context, cancel) {
// Scroll to bottom after every rebuild
if (scrollController.hasClients) {
scrollController.jumpTo(
scrollController.position.maxScrollExtent,
);
}
// Optionally cancel if a condition is met
if (messages.length > 100) {
cancel(); // Stop auto-scrolling after 100 messages
}
});
return ListView.builder(
controller: scrollController,
itemCount: messages.length,
itemBuilder: (context, index) => Text(messages[index]),
);
}
}
Implementation
void callAfterEveryBuild(
void Function(BuildContext context, void Function() cancel) callback) {
assert(_activeWatchItState != null,
'callAfterEveryBuild can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');
_activeWatchItState!.callAfterEveryBuild(callback);
}