Search code examples
flutterdartscrollviewcustomscrollview

Flutter - How scroll to SliverPersistentHeader position?


CustomScrollView(
     SliverToBoxAdapter(), // firstBox
     SliverPersistentHeader(pinned:true),
     SliverToBoxAdapter(), // secondBox
)

I have a button on this page, when I click this button, how let SliverPersistentHeader scroll to top programmatically?
Addition: firstBox's height is uncertain.


Solution

  • Initalize a GlobalKey in that widget.

        final GlobalKey globalKey = GlobalKey();
    

    Then pass it to the widget you want to scroll to:

      CustomScrollView(
       slivers: [
         SliverToBoxAdapter(), // firstBox
         SliverPersistentHeader(pinned: true, delegate: null,),
         SliverToBoxAdapter(
           key: globalKey,
         ),
       ],
     )
    

    Then the button onPressed should be like this:

      onPressed: () {
                Scrollable.ensureVisible(
                globalKey.currentContext!,
                duration: const Duration(seconds: 1),
                );
            },