Last active
July 27, 2022 05:23
-
-
Save Mufaddal1125/a54143eb680ce9c125ed38d4e19200f0 to your computer and use it in GitHub Desktop.
scroll to widget method
This file contains hidden or 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
void _scrollToWidget() async { | |
// find the index of fruit to scroll to in fruits | |
// let's scroll to Mandarina | |
final index = fruits.indexOf('Mandarina'); | |
// get global key of Mandarina | |
final key = _fruitKeys[index]; | |
// find the render box of Mandarina | |
var box = key.currentContext?.findRenderObject(); | |
// if box is not in the view port, scroll to it | |
if (box == null) { | |
// speed to scroll to Mandarina | |
double scrollSpeed; | |
// find the key of the render box which is currently in view | |
var currentKeyIndex = _fruitKeys.indexWhere( | |
(element) => element.currentContext?.findRenderObject() != null); | |
// if currently visible fruit is before fruit which we need to scroll to, | |
// then speed should be negative because we want to scroll up otherwise positive i.e sroll down | |
scrollSpeed = currentKeyIndex > index ? 100 : -100; | |
// scroll until render object is found | |
while (box == null) { | |
var offset = _scrollController.offset - scrollSpeed; | |
await _scrollController.animateTo( | |
offset, | |
duration: const Duration(milliseconds: 1), | |
curve: Curves.easeInOut, | |
); | |
box = key.currentContext?.findRenderObject(); | |
} | |
} | |
_scrollController.position.ensureVisible( | |
box, | |
// How far into view the item should be scrolled (between 0 and 1) | |
// with 1 being the bottom of the view and 0 being the top. | |
alignment: 0.2, | |
duration: const Duration(milliseconds: 200), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment