VisibilityDetector: A Comprehensive Guide
Published on by Flutter News Hub
VisibilityDetector is a Flutter widget that wraps another widget and provides real-time visibility updates. It reports when the VisibilityDetector widget (and thus its child) transitions between visible and invisible states.
Key Features
- Visibility Changes: Reports visibility changes for its child widget.
- Coalesced Callbacks: Defers and groups callbacks to avoid excessive UI updates.
- Update Interval: Controls the frequency of callback invocations.
- Immediate Triggering: Trigger callbacks immediately using VisibilityDetectorController.notifyNow().
Example Usage
@override Widget build(BuildContext context) { return VisibilityDetector( key: Key('my-widget-key'), onVisibilityChanged: (visibilityInfo) { var visiblePercentage = visibilityInfo.visibleFraction * 100; debugPrint('Widget $ is $% visible'); }, child: someOtherWidget, ); }
Widget Tests
For widget tests:
VisibilityDetectorController.instance.updateInterval = Duration.zero;
This ensures immediate updates and avoids "Timer is still pending" assertions.
Known Limitations
- Does not consider widget opacity.
- Visibility fraction may not account for overlapping widgets.
Implementation Details
VisibilityDetector uses a Timer to periodically check the widget's visibility with a default interval of Duration(milliseconds: 200). When the visibility changes, the onVisibilityChanged callback is triggered.
Benefits of VisibilityDetector
- Efficient Updates: Coalesces callbacks to minimize unnecessary UI updates.
- Fine-grained Control: Allows for immediate callback triggering or setting custom update intervals.
- Improved Performance: Avoids redundant visibility checks by deferring updates.
Conclusion
VisibilityDetector is a valuable tool for monitoring the visibility of widgets in Flutter applications. Its coalesced updates and customizable features make it suitable for complex UI scenarios where efficient visibility tracking is essential.