flutterlistviewlistviewitemflutter-listview

Flutter: performance issue in long lists with random colors


I have a List of items, each item has a color, when the list passes like 15 items the color of the items that are off-screen changes. I've tried with ListView.builder and ListView.custom and it's the same result.

Here's the code I use for the list:

ListView.builder(
          itemBuilder: (ctx, index) {
            return NoteItem(
              key: ValueKey(notes[index].id),
              note: notes[index],
              deleteNote: deleteNote,
            );
          },
          itemCount: notes.length,
          findChildIndexCallback: (Key key) {
            final ValueKey valueKey = key;
            final String data = valueKey.value;
            final index = notes.indexWhere((nt) => nt.id == data);
            return index >= 0 ? index : null;
          },
        ),

Before Scrolling (example)

After Scrolling (example)

also, Is there any way to not have the same color as the last item added in the list? I tried to add .toSet().toList() to my list of colors. but it still generate 2 of the same color in-a-row at some point.

Here's my colors list:

     Color _bgColor;

  @override
  void initState() {
    const availableColors = [
      Color.fromARGB(255, 170, 171, 168),
      Color.fromARGB(255, 188, 122, 119),
      Color.fromARGB(255, 205, 155, 157),
      Color.fromARGB(255, 219, 199, 201),
      Color.fromARGB(255, 136, 167, 149),
      Color.fromARGB(255, 230, 192, 181),
      Color.fromARGB(255, 184, 208, 228),
    ];

    _bgColor = availableColors[Random().nextInt(7)];

    super.initState();
  }

Can you help?

I'm new to flutter and I was trying to apply what I've learned so far so I'm sorry if the question is dumb :) also sorry for my bad English.

Thanks in advance.


Solution

  • I would suggest to pass the index to the NoteItem, like this for example

    return NoteItem(
      key: ValueKey(notes[index].id)
      note: notes[index],
      deleteNote: deleteNote,
      index: index
    );
    

    and then change

    _bgColor = availableColors[Random().nextInt(7)];
    

    to

    _bgColor = availableColors[widget.index % 7];
    

    It won't be random anymore then, but at least consistent and no duplicate colors after each other