You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断Map返回值为空?ListView搜索无结果显示空图标求助

实现带搜索的ListView空状态显示

你可以通过先提取过滤后的列表,再根据列表是否为空来切换显示内容,具体修改如下:

修改后的代码

// 先提取过滤后的todo列表,方便后续判断
final filteredTodos = controller.todo.value.where((element) {
  if (controller.search.value != '') {
    return element.labels!
            .toString()
            .toLowerCase()
            .contains(controller.search.value.toLowerCase());
    // 额外优化:把搜索值也转小写,避免大小写不匹配的问题
  }
  return true;
}).toList();

ListView(
  children: filteredTodos.isEmpty 
      ? [
          // 空状态:显示空图标,用Center包裹实现居中
          Center(
            child: Icon(
              Icons.inbox_outlined,
              size: 60,
              color: Colors.grey[400],
            ),
          )
        ]
      : filteredTodos.map((todo) {
          return Text(todo.name);
        }).toList(),
)

关键改动说明

  • 把过滤逻辑单独提取成filteredTodos变量,既避免重复计算,也方便判断列表是否为空
  • 用三元运算符filteredTodos.isEmpty ? ... : ...实现状态切换:为空时返回空状态组件列表,否则返回原有的todo项列表
  • 可根据需求替换空状态的Icon为自定义图片,或补充"暂无数据"的文字提示

内容的提问来源于stack exchange,提问作者Venkat Cpr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:20:49