Skip to content

Instantly share code, notes, and snippets.

@slightfoot
Last active January 9, 2022 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save slightfoot/7a1937a7d5f0bf61d09be4db90d04ebe to your computer and use it in GitHub Desktop.
Save slightfoot/7a1937a7d5f0bf61d09be4db90d04ebe to your computer and use it in GitHub Desktop.
Scroll content to widget with key - by Simon Lightfoot - 13/11/2019
// MIT License
//
// Copyright (c) 2021 Simon Lightfoot
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import 'package:flutter/material.dart';
// NOTE: context of widget inside scrollable but above the widgets with the keys
bool scrollToKey(BuildContext context, Key key) {
Element? found;
void visitElement(Element el) {
if (el.widget.key == key) {
found = el;
return;
}
el.visitChildren(visitElement);
}
context.visitChildElements(visitElement);
if (found == null) {
return false;
}
final scrollable = Scrollable.of(context);
final box = found?.findRenderObject() as RenderBox?;
if(scrollable == null || box == null){
return false;
}
final offset = box.localToGlobal(
Offset.zero,
ancestor: scrollable.context.findRenderObject(),
);
scrollable.position.animateTo(
scrollable.position.pixels + offset.dy,
duration: const Duration(milliseconds: 350),
curve: Curves.easeOutExpo,
);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment