skip to Main Content

How can I scroll to specific section in flutter ?

I have webpage with

  • header
  • main
  • footer

When i click footer, I want to go to the footer section.

I just know we have to use ScrollController but ran out of resources to figure out solution, seems easy but couldn’t find a solution.

Headsup, It is not just simple ListView, so ListView's approach to go to specific index wouldn’t work.

2

Answers


  1. Chosen as BEST ANSWER
    1. Create Global Key
       GlobalKey _containerKey = GlobalKey();
      
    2. Assign key to the section to scroll to:
      Container(
        key: _containerKey,
        // other footer widgets
      ),
      
    3. Go to the section on onPressed using _containerKey.currentContext:
      onPressed: () {
        Scrollable.ensureVisible(
          _containerKey.currentContext!,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut,
        );
      },
      

  2. You can use Scrollable.ensureVisible(contextToBeVisible)

    Just pass the context of the e.g. footer and the scrolling will happen if e.g. combined with an onTap event:

    onTap: () => Scrollable.ensureVisible(contextToBeVisible)
    

    Official docs: https://api.flutter.dev/flutter/widgets/Scrollable/ensureVisible.html

    And there are numerous examples here on SO.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search