Animate Scroll Controller to top of ListView.builder after Navigation

3,095

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]));
Share:
3,095
DrainBramage
Author by

DrainBramage

Updated on December 06, 2022

Comments

  • DrainBramage
    DrainBramage over 1 year

    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!

    • boformer
      boformer over 5 years
      Why don't you just use a non-reversed ListView that starts at the top by default?
    • DrainBramage
      DrainBramage over 5 years
      How can I set a ListView that starts with newest posts at top by default? The ones I have worked with starts with user seeing the oldest value at bottom if reversed = true (and user scrolls up to see newer posts), or start with user seeing oldest value at top if reversed = false (and user scrolls down to see newer posts). Thanks
    • boformer
      boformer over 5 years
      Well, you just have to inverse the list of items that is given into the ListView. I will post a quick example as an answer.