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

如何为SearchResultCell添加搜索无结果时的「未找到结果」提示文本

实现方案

你只需要两步即可完成需求,全程不需要修改Container的属性,提示文本也完全封装在SearchResultCell内部:


1. 改造SearchResultCell组件,新增空状态逻辑

给组件新增两个可选入参,内部做条件渲染:

class SearchResultCell extends StatelessWidget {
  final dynamic search;
  // 新增空状态控制参数
  final bool isNoResult;
  final String? emptyHint;

  const SearchResultCell({
    super.key,
    this.search,
    this.isNoResult = false,
    this.emptyHint = "未找到结果",
  });

  @override
  Widget build(BuildContext context) {
    // 空状态时渲染提示文本
    if (isNoResult) {
      return Center(
        child: Text(
          emptyHint,
          style: const TextStyle(color: Colors.grey, fontSize: 14),
        ),
      );
    }
    // 原有正常搜索结果的渲染逻辑保持不变
    return 你原来的搜索结果布局代码;
  }
}

2. 调整外层调用逻辑

根据搜索结果数组_search是否为空,控制传入SearchResultCell的参数即可:

child: Container(
    margin: EdgeInsets.only(left: 25, right: 25, bottom: 15),
    height: 50,
    child: _search.isEmpty
      // 无结果时传入空状态标识
      ? const SearchResultCell(isNoResult: true)
      // 有结果时正常渲染原有逻辑
      : SearchResultCell(
          search: this._search[index],
        )
)

如果你外层是用ListView.builder批量渲染搜索结果,可以调整列表的计数和生成逻辑:

ListView.builder(
  itemCount: _search.isEmpty ? 1 : _search.length,
  itemBuilder: (context, index) {
    return Container(
      margin: const EdgeInsets.only(left: 25, right: 25, bottom: 15),
      height: 50,
      child: _search.isEmpty 
        ? const SearchResultCell(isNoResult: true)
        : SearchResultCell(
            search: this._search[index],
          ),
    );
  }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:15:03