Flutter ListView.builder()动态列表-显示无限重复的条目 [英] Flutter ListView.builder() dynamic list - shows inifinitely repeating entries
问题描述
我有一个很大的〜5K物品清单。
I have a large, ~5K items list.
我想做的就是为这些物品写一个搜索视图。
What I wanted to do was to write a search view for these items.
我尝试了以下操作-
List<String> items;
String query;
ListView.builder(
itemBuilder: (context, index) {
for (int i = index; i < items.length; i++) {
var item = items[i];
if (item.contains(query)) {
return ItemTile(item);
}
}
}
这可以有效地渲染和搜索元素,但是问题在于它最终无限地重复了列表中的最后一项。
This renders and searches for elements efficiently, but the problem is that it ends up repeating the last item in the list infinitely.
我想那是因为我没有提供 itemCount
。
I guess that's because I wasn't providing an itemCount
.
所以我试图在 Stateful
小部件中跟踪自己过滤的项目数。
So I tried to keep track of the number of filtered items myself, inside a Stateful
Widget.
var _count = 1;
_queryController.addListener(() {
setState(() => _count = 1);
});
ListView.builder(
itemBuilder: (context, index) {
for (int i = index; i < items.length; i++) {
var item = items[i];
if (item.contains(query)) {
setState(() => _count += 1);
return ItemTile(item);
}
}
itemCount: _count;
}
但是我收到一个错误,说- setState ()或markNeedsBuild()在构建过程中调用。
But then I receive an error, saying - setState() or markNeedsBuild() called during build.
什么是正确的方法,而不必为每个查询完全搜索项目?
What would be the right way to do this, without compltely searching through items for each query?
(我的目标是搜索按需键入UX)
(I was aiming for a search-as-you-type UX)
推荐答案
您可以在将列表传递给构建器之前尝试对其进行过滤。
You could try filtering the list before you pass it to the builder.
List<String> items;
List<String> _queryResults;
String query;
_queryResults = items.where((item) => item.contains(query)).toList();
然后可以将其传递到ListView.builder,而不必一遍又一遍地设置状态。不确定与其他选项相比其性能如何,应该不会有太大区别,因为在大多数情况下,过滤后的列表可能会很短。比在构建器中进行过滤和设置状态要干净得多,因此我至少要对其进行测试。
Which could then be passed to the ListView.builder without having to set state over and over. Not sure how it would be in performance compared to other options, shouldn't be a big difference as the filtered list will likely be a lot short in most cases. It's a lot cleaner than doing filtering and setting state inside the builder, so I would at least test it out.
此外,如果要进行过滤,还应该对过滤进行反跳处理一种按需搜索的解决方案,这意味着您在每次输入后等待500毫秒或一段合适的持续时间,以查看用户在进行过滤之前是否键入了更多内容。将为您节省很多不必要的电话,并使您的解决方案性能更好。
Also you should debounce the filtering if you're going for a search-as-you-type solution, which means you wait like 500ms or some fitting duration after each input to see if the user types more before you do the filtering. Will save you a lot of unnecessary calls and make your solution perform better.
这篇关于Flutter ListView.builder()动态列表-显示无限重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!