I’m developing a widget using SingleChildScrollView with a horizontal scroll direction (Axis.horizontal). However, I want the initial scroll position to be centered, rather than starting at the beginning. I’ve searched extensively for a solution but haven’t found one yet. How can I achieve this?
As for now, I’ve tried a solution generated from ChatGPT. What it does is, it first calculates the complete width of the scroll, which is about 5250 according to my print output. However, it doesn’t come to the center. It gives a jumping effect from the center to the start as I’m unsure to make it stay at the center.
void _scrollToMiddle() {
if (_scrollWidth > 0) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollController.jumpTo(_scrollWidth / 2);
});
setState(() {
_isScrollPositionSet = true;
});
}
}
void _calculateScrollWidth() {
final renderObject = _scrollKey.currentContext?.findRenderObject();
if (renderObject is RenderBox) {
final size = renderObject.size;
setState(() {
_scrollWidth = size.width;
});
if (!_isScrollPositionSet) {
_scrollToMiddle();
}
}
}