Search code examples
listviewnavigationdartscrollviewflutter

Animate Scroll Controller to top of ListView.builder after Navigation


ers,

Goal: To navigate to the page with my ListView.builder and immediately see the the most recent (top) of the list, and scroll down to see older entries.

I have a ListView.builder with 100 items(#1-100). I can reverse the list to get a facebook-like feed with the most recent (100) first.

Using a Floating action button over the ListView, I can use the below to jump to the top of the list successfully:

 _postscrollController.animateTo(     
 _scrollController.position.maxScrollExtent 
                            curve: Curves.easeOut,
                            duration: const Duration(milliseconds: 10))

However, I cannot automatically invoke the above when navigating TO the page that contains the ListView.builder. When I open the app and navigate to the list from the homescreen, it starts me at the very bottom of the list (1) and I have to scroll up to get to the top.

Any advice/suggestions would be greatly appreciated.

Gooooo FLUTTER!


Solution

  • Here is a very simple example how to reverse a list, and not the whole ListView:

    import 'package:flutter/material.dart';
    
    main() => runApp(MaterialApp(home: MyHomePage()));
    
    List<String> listData = [
      'oldest',
      'older',
      'old',
      'new',
      'newer',
      'newest',
    ];
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        // reverse the order of the list data
        List<String> reversedListData = listData.reversed.toList();
    
        return Scaffold(
          appBar: AppBar(),
          body: ListView.builder(
            itemCount: reversedListData.length,
            itemBuilder: (BuildContext context, int index) {
              // use reversed list to build list item
              return ListTile(title: Text(reversedListData[index]));
            },
          ),
        );
      }
    }
    

    Or as an alternative, you could also just translate the index to count down:

    int reversedIndex = listData.length - 1 - index;
    return ListTile(title: Text(listData[reversedIndex]));