Simon B
Simon B

Reputation: 587

Flutter - How to add items on the top of a Listview builder?

I have a Listview.builder on my app to add player in my game. As I show in the gif here:

enter image description here

What I want to do is, instead of adding the player "test2" under the player "test", I want to add it on top of him... I tried the reverse method, but if I do that, the Listview start from the bottom of the screen...

Do you have any idea to solve this ?

Here is my code :

      body: ListView.builder(
          itemCount: Provider.of<PlayerProvider>(context).getPlayerList.length,
          itemBuilder: (context, index) {
            return Column(
              children: [
                PlayerDismissible(index),
                Divider(
                  color: Colors.orange,
                  height: 0,
                )
              ],
            );
          }),
      bottomSheet: BottomPlayerBar(),

Upvotes: 1

Views: 3886

Answers (2)

yelliver
yelliver

Reputation: 5946

Adding to the top of a list is not efficient because it needs to shift all the remaining items of the list to the right. Just add to the list by add() and get the item by reversing the index:

PlayerDismissible(length - index - 1)

Upvotes: 1

Jigar Patel
Jigar Patel

Reputation: 5423

When you add new player to the list you can use insert method on List to add new player as the first one in the list like..

Player newPlayer = Player('name');
playersList.insert(0, newPlayer);

Upvotes: 2

Related Questions