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

Flutter应用报错:The method 'call' was called on null 求助排查

Flutter SearchBar 报错:The method 'call' was called on null

错误原因分析

报错核心是SearchBar的回调参数传入了非函数值(最终为null),当组件尝试调用这些回调时,就会触发call方法调用null的错误,具体问题出在两处:

  1. onSearch参数的离线分支
    你当前的写法是直接执行_showToast(constants.offlineErrorMessage),如果_showToast返回void,这个分支的结果就是null,但onSearch要求传入一个Future<List<BookList>> Function(String)类型的函数,离线分支不符合参数类型要求。

  2. onItemFound参数
    直接传递_showToast("Data Found")是执行方法后的结果(void类型对应null),但onItemFound需要的是一个接收搜索结果项的可调用回调函数。

另外你的search函数存在语法错误(多余的闭合括号),也需要修正。

修复方案

修复后的body.dart代码

Widget build(BuildContext context) {
  return Scaffold(
    body: SafeArea(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        child: SearchBar<BookList>(
          onSearch: _isOnline
              ? search
              : (query) {
                  // 离线时返回符合要求的Future,同时提示离线信息
                  _showToast(constants.offlineErrorMessage);
                  return Future.value([]);
                },
          onItemFound: (item) => _showToast("Data Found"), // 传递回调函数而非执行结果
          loader: const Center(child: CircularProgressIndicator()),
          emptyWidget: Center(
            child: SelectableText.rich(
              _isOnline
                  ? const TextSpan(
                      style: TextStyle(fontSize: 18),
                      children: [
                        TextSpan(text: "No Data found!"),
                      ],
                    )
                  : TextSpan(text: constants.offlineErrorMessage),
            ),
          ),
          textStyle: const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
        ),
      ),
    ),
  );
}

修复后的search函数

Future<List<BookList>> search(String search) async {
  try {
    if (!isLoadingFirstTime) _showToast("Tap on image to maximize");
    List<BookList> finalList = await fetchDownloadableLink(bookList);
    isLoadingFirstTime = true;
    return finalList;
  } catch (e) {
    throw Exception("搜索失败: $e");
  }
}

关键修复说明

  • onSearch离线分支:改为返回符合参数类型要求的函数,执行提示后返回空列表的Future,满足SearchBar的回调规范。
  • onItemFound参数:改用箭头函数传递可调用的回调,而非直接执行方法的结果。
  • 修正search函数语法:移除多余的闭合括号,优化异常捕获的可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:35:24