landfire13224
landfire13224

Reputation: 437

How to get child scroll offset position in ScrollView in Flutter

I make a CustomScrollView widget that contains:

The SliverPersistentHeader would be the description of the item in the SliverGrid, once it tapped (I wrapped it with GestureDetector) I want the scroll offset to change in the middle where the SliverPersistentHeader is.

How to do that? ScrollController seems only aware of the scroll extent, so far I do not yet see any property in ScrollView (which CustomScrollView inherit) that could give me the offset position of an individual widget.

Upvotes: 5

Views: 5607

Answers (2)

Jagrit Nokwal
Jagrit Nokwal

Reputation: 11

final GlobalKey gKey = GlobalKey(debugLabel: "gkey");
void scrollToMainItemsTop() {
  // Find the context of the widget associated with the GlobalKey
  final BuildContext? context = gKey.currentContext;
  // Ensure the context is not null
  if (context != null) {
    // Ensure the widget associated with the GlobalKey is visible in the viewport
    Scrollable.ensureVisible(
      context,
      duration: const Duration(milliseconds: 500),
      curve: Curves.easeInOut,
    );
  }
}

In case of CustomScrollView this works for me assign your sliver this gKey

Upvotes: 1

mkobuolys
mkobuolys

Reputation: 5343

Based on the documentation, ScrollController has an offset property: https://api.flutter.dev/flutter/widgets/ScrollController/offset.html So that's the way on how to get the current offset.

If you want to scroll to a specific position, you can use the animateTo method: https://api.flutter.dev/flutter/widgets/ScrollController/animateTo.html. For instance:

scrollController.animateTo(123, duration: Duration(seconds: 1), curve: Curves.easeIn);

In this case, you should calculate the offset value where you want to scroll (123 in the example).

In case you need to "find" that offset value, one way is to use keys on the widget and get the position of it by using the RenderObject. That's explained in this answer: https://stackoverflow.com/a/54303022/15427566

Upvotes: 2

Related Questions