Reputation: 890
I want to add space/padding for a scrollbar when it is visible.
How can I find out, if a scrollbar is visible in a flutter widget?
Upvotes: 1
Views: 655
Reputation: 30879
Old question, but as of 2025 you can use widget DetectScroll
from package assorted_layout_widgets.
DetectScroll
can detect if a scrollbar is likely visible, and also tell you the width of the scrollbar. This is useful for positioning widgets relative to the scrollbar, so that the scrollbar doesn't overlap them. This can be important when the scrollbar is permanently visible, usually on the Web and desktop.
Wrap the scrollable you care about directly with a DetectScroll
:
DetectScrollbar(
child: SingleChildScrollView(
child: Column( ...
...
);
Then, in a descendent widget, you can get the current scroll state and the scrollbar width:
bool isScrolled = DetectScroll.of(context).isScrolled;
double width = DetectScroll.of(context).scrollbarWidth;
For example, suppose you want to add a help button to the top-right corner of a scrollable, and account for the scrollbar width only if it's visible:
bool isScrollbarPresent = DetectScroll.of(context).isScrolled;
double width = DetectScroll.of(context).scrollbarWidth;
return Stack(
children: [
child,
Positioned(
right: isScrollbarPresent ? width : 0,
top: 0,
child: HelpButton(),
),
],
);
Note I'm the package author.
Upvotes: 0
Reputation: 890
Through the following I could find out if there is a scrollbar
NotificationListener<ScrollMetricsNotification>(
onNotification: (notification) {
setState(() {
hasScrollbar = (notification.metrics.maxScrollExtent > 0);
});
},
and when hasScrollbar is true I add padding for it:
padding: hasScrollbar ? myThemeData.screenPadding.copyWith(right: 20.scaled()) : myThemeData.screenPadding,
Upvotes: 1
Reputation: 176
this lib can help you to do it https://pub.dev/packages/visibility_detector
@override
Widget build(BuildContext context) {
return VisibilityDetector(
key: Key('my-widget-key'),
onVisibilityChanged: (visibilityInfo) {
var visiblePercentage = visibilityInfo.visibleFraction * 100;
debugPrint(
'Widget ${visibilityInfo.key} is ${visiblePercentage}% visible');
},
child: someOtherWidget,
);
}
Upvotes: 0