Skip to content

Instantly share code, notes, and snippets.

Last active Aug 11, 2019
What would you like to do?
_scrollTo(int index) {
// get the screen width. This is used to check if we have an element off screen
double screenWidth = MediaQuery.of(context).size.width;
// get the button we want to scroll to
RenderBox renderBox = _keys[index].currentContext.findRenderObject();
// get its size
double size = renderBox.size.width;
// and position
double position = renderBox.localToGlobal(;
// this is how much the button is away from the center of the screen and how much we must scroll to get it into place
double offset = (position + size / 2) - screenWidth / 2;
// if the button is to the left of the middle
if (offset < 0) {
// get the first button
renderBox = _keys[0].currentContext.findRenderObject();
// get the position of the first button of the TabBar
position = renderBox.localToGlobal(;
// if the offset pulls the first button away from the left side, we limit that movement so the first button is stuck to the left side
if (position > offset) offset = position;
} else {
// if the button is to the right of the middle
// get the last button
renderBox = _keys[_icons.length - 1].currentContext.findRenderObject();
// get its position
position = renderBox.localToGlobal(;
// and size
size = renderBox.size.width;
// if the last button doesn't reach the right side, use it's right side as the limit of the screen for the TabBar
if (position + size < screenWidth) screenWidth = position + size;
// if the offset pulls the last button away from the right side limit, we reduce that movement so the last button is stuck to the right side limit
if (position + size - offset < screenWidth) {
offset = position + size - screenWidth;
// scroll the calculated ammount
_scrollController.animateTo(offset + _scrollController.offset,
duration: new Duration(milliseconds: 150), curve: Curves.easeInOut);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment