Flutter:随机颜色的长列表中的性能问题



我有一个项目列表,每个项目都有一个颜色,当列表像15个项目一样经过时,屏幕外项目的颜色会发生变化。我试过使用ListView.builder和ListView.custom,结果是一样的。

这是我用于列表的代码:

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;
},
),

滚动前(示例(

滚动后(示例(

还有,有没有办法不让颜色与列表中添加的最后一个项目相同?我试着把.toSet((.toList((添加到我的颜色列表中。但是它在某个点上仍然在一行中生成2个相同颜色的。

这是我的颜色清单:

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();
}

你能帮忙吗?

我是个初来乍到的人,我一直在努力应用我迄今为止学到的东西,所以如果这个问题很愚蠢,我很抱歉:(也很抱歉我的英语不好。

提前谢谢。

我建议将索引传递给NoteItem,例如

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

然后更改

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

_bgColor = availableColors[widget.index % 7];

那时它将不再是随机的,但至少是一致的,并且在每次之后没有重复的颜色

检查当前颜色是否与以前的颜色相同,然后再次选择颜色。如果你不能暗示,那就告诉我我会帮你的。

不要生成随机颜色。只需将索引也传递给NoteItem类,然后设置索引,颜色将按顺序选择。

Color _bgColor;静态int索引=0;

@超控

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[index % 7];
super.initState();

}

最新更新