Flutter logo

Flutter: enable scroll-to-top for nested Scaffolds (e.g. in IndexedStack)

Written by

in

When using nested Scaffolds (e.g. in combination with IndexedStack), the PrimaryScrollController is not usable by default. An IndexedStack will load all subviews so scroll-to-top will change all scrollable views at the same time, even if they are not visible or it simply does not work, because the PrimaryScrollController can only be attached to a single Scaffold.

To overcome this issue, the scrolls_to_top package can be used. This also works for nested Scaffolds. The functionality of the package is described in this post (here is the english translation).

The following code example shows the usage. This is how to use ScrollsToTop within each children of IndexedStack:

  final _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      primary: true,
      body: ScrollsToTop(
        onScrollsToTop: (event) {
          // onScrollsToTop will be called on each touch event, so check if the view is currently visible
          if (!widget.isOnScreen) return;

          _scrollController.animateTo(
            event.to,
            duration: event.duration,
            curve: event.curve,
          );
        },
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: 100,
          controller: _scrollController,
        ),
      ),
    );
  }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *