Created
January 10, 2023 12:41
-
-
Save bambinoua/9e4faa762bfc62ee35a07898fccc99ff to your computer and use it in GitHub Desktop.
Example of using ScrollbarPainter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
const double _kScrollbarThickness = 6.0; | |
class MyScrollbar extends StatefulWidget { | |
final ScrollableWidgetBuilder builder; | |
final ScrollController scrollController; | |
const MyScrollbar({ | |
Key key, | |
this.scrollController, | |
@required this.builder, | |
}) : assert(builder != null), | |
super(key: key); | |
@override | |
_MyScrollbarState createState() => _MyScrollbarState(); | |
} | |
class _MyScrollbarState extends State<MyScrollbar> { | |
ScrollbarPainter _scrollbarPainter; | |
ScrollController _scrollController; | |
Orientation _orientation; | |
@override | |
void initState() { | |
super.initState(); | |
_scrollController = widget.scrollController ?? ScrollController(); | |
WidgetsBinding.instance.addPostFrameCallback((_) { | |
_updateScrollPainter(_scrollController.position); | |
}); | |
} | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
_scrollbarPainter = _buildMaterialScrollbarPainter(); | |
} | |
@override | |
void dispose() { | |
_scrollbarPainter.dispose(); | |
super.dispose(); | |
} | |
ScrollbarPainter _buildMaterialScrollbarPainter() { | |
return ScrollbarPainter( | |
color: Theme.of(context).highlightColor.withOpacity(1.0), | |
textDirection: Directionality.of(context), | |
thickness: _kScrollbarThickness, | |
fadeoutOpacityAnimation: const AlwaysStoppedAnimation<double>(1.0), | |
padding: MediaQuery.of(context).padding, | |
); | |
} | |
bool _updateScrollPainter(ScrollMetrics position) { | |
_scrollbarPainter.update( | |
position, | |
position.axisDirection, | |
); | |
return false; | |
} | |
@override | |
void didUpdateWidget(MyScrollbar oldWidget) { | |
super.didUpdateWidget(oldWidget); | |
_updateScrollPainter(_scrollController.position); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return OrientationBuilder( | |
builder: (context, orientation) { | |
_orientation ??= orientation; | |
if (orientation != _orientation) { | |
_orientation = orientation; | |
_updateScrollPainter(_scrollController.position); | |
} | |
return NotificationListener<ScrollNotification>( | |
onNotification: (notification) => | |
_updateScrollPainter(notification.metrics), | |
child: CustomPaint( | |
painter: _scrollbarPainter, | |
child: widget.builder(context, _scrollController), | |
), | |
); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment