Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic expand/collapse SliverAppBar

Tags:

flutter

If there is a way to implement automatically scrolling the SliverAppBar to a collapsed or expanded state at the moment the user stops scrolling in an intermediate position (between collapsedHeight and expandedHeight of SliverAppBar).

enter image description here

like image 828
Victor K Avatar asked Feb 03 '26 10:02

Victor K


1 Answers

Not sure if this is the best approach, but it works:

     final _controller = ScrollController();

     ...

     Scaffold(
        body: NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollEndNotification &&
            scrollNotification.depth == 0) {
          final minExtent = scrollNotification.metrics.minScrollExtent;
          final maxExtent = scrollNotification.metrics.maxScrollExtent;
          final middle = (maxExtent - minExtent) / 2;
          final pos = scrollNotification.metrics.pixels;

          double scrollTo;
          if (minExtent < pos && pos <= middle)
            scrollTo = minExtent;
          else if (middle < pos && pos < maxExtent) scrollTo = maxExtent;
          if (scrollTo != null)
            // Doesn't work without Timer
            Timer(
                Duration(milliseconds: 1),
                () => _controller.animateTo(scrollTo,
                    duration: Duration(milliseconds: 300),
                    curve: Curves.ease));
        }
        return false;
      },
      child: NestedScrollView(
          controller: _controller,
          ...

working example

like image 147
Victor K Avatar answered Feb 06 '26 11:02

Victor K