Dynamically adding items to top of SliverList – state of previous item is incorrectly kept


I have a List recentlyScanned of items that I am drawing in a SliverList like so:

  delegate: SliverChildBuilderDelegate(
    (BuildContext context, int index) {
      return ListTileItemProduct2(data: model.recentlyScanned[index]);
    childCount: model.recentlyScanned.length,

Each item has colour coding to denote its status which is applied when the list. I use list.add(item) successfully to dynamically add an item to the bottom of the list – everything looks great. The issue I now face is I want newly/dynamically added items to appear at the top of the list. I have tried a few methods:

  1. recentlyScanned.reverse.toList() – changes the source to be sent in reverse order
  2. recentlyScanned.insert(0, item) – adding an item to the index 0 of the list, bumping everything down
  3. when an item is added, resort the list using recentlyScanned.sort((a,b) => a.compareTo(b));

While each of these functions technically work (they sort the list into the correct "reversed" order) the state of the previous item is retained in the SliverList. This means the status colour of the new item now at the top of the list inherits the color if the item it replaced, the one previously at the top now inherits the second items state, etc. This does not happen when adding to the bottom of the list.

Any ideas how I can either a) rebuild the entire SliverList when an item is added or b) have the Sliver list work as it usually would when adding an item to the bottom of the array, but in reverse?


You need to pass a unique key to the ListTile – this forces flutter to refresh the list vs its usual (aggressive and fast) caching

  key: Key('UniqueString'),

Answered By – user1048175

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *