Flutter应用报错:The method 'call' was called on null 求助排查
Flutter SearchBar 报错:The method 'call' was called on null
错误原因分析
报错核心是SearchBar的回调参数传入了非函数值(最终为null),当组件尝试调用这些回调时,就会触发call方法调用null的错误,具体问题出在两处:
onSearch参数的离线分支
你当前的写法是直接执行_showToast(constants.offlineErrorMessage),如果_showToast返回void,这个分支的结果就是null,但onSearch要求传入一个Future<List<BookList>> Function(String)类型的函数,离线分支不符合参数类型要求。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
相关产品推荐
相关产品推荐

