我有一个由 ListView.builder 呈现的列表,我使用一个函数来检查是否正在搜索列表中的对象,但我想在没有找到对象时显示一个屏幕。所以用户知道没有找到任何东西,但我正在苦苦挣扎,代码看起来像这样:
Container OnlyShow = Container(
child: ListView.builder(
itemCount: myList.length,
itemBuilder: (context, index) {
if (searchfunction(myList[index]) == true) {
return myListObject(myList[index]);
} else {
return Container(height: 0, width: 0,);
}
},
),
);
搜索功能本身不是问题我只想知道如果 ListView.builder 只返回空容器我怎么能知道,因为这意味着没有对象等同于搜索因此什么也找不到。
我试过类似的东西:
Container OnlyShow = Container(
child: ListView.builder(
itemCount: myList.length,
itemBuilder: (context, index) {
if (searchfunction(myList[index]) == true) {
if (howManyObjectsAreFalse > 0) {
howManyObjectsAreFalse--;
dismissNoResultsFoundScreen();
}
return myListObject(myList[index]);
} else {
if (howManyObjectsAreFalse < myList.length) {
howManyObjectsAreFalse++;
}
if (howManyObjectsAreFalse == myList.length) {
showNoResultsFoundScreen();
}
return Container(height: 0, width: 0,);
}
},
),
);
int howManyObjectsAreFalse = 0;
它应该像这样工作,当返回一个空容器时,计数会增加,当返回结果时,计数会减少,因此当计数达到列表的长度时,将显示 NoResultScreen。
它确实有效,但有一些奇怪的异常(exception),有时计数似乎在值之间波动,即使 ListView.builder 只返回空容器。
注意:列表不为空我只是为列表中不等于搜索值的每个对象返回一个空容器。所以我不会减少列表或其他内容
我希望有人能帮助我更好地实现这一目标。
最佳答案
@pskink 给出的答案起到了作用:
child: myList.where(searchfunction).isEmpty ? Text('nothing was found') : ListView.builder(...)
关于flutter - 检查 ListView.builder 是否只返回空容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65786913/