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

Flutter报错:参数类型‘Null’无法分配给参数类型‘String’求解决

解决Flutter搜索页面关闭按钮报错:参数类型“Null”无法分配给参数类型“String”

问题原因

你的SearchDelegate类应该声明为了泛型String类型(比如class YourSearchDelegate extends SearchDelegate<String>),因此close方法的第二个参数要求传入String类型的值,但你传入了null,导致类型不匹配触发报错。

解决方案

方案1:直接用Navigator.pop关闭页面

如果不需要向底层路由返回任何结果,直接替换为Navigator.pop(context)即可:

@override
Widget buildLeading(BuildContext context) {
  return IconButton(
    icon: const BackButtonIcon(),
    color: Theme.of(context).primaryColor,
    onPressed: () {
      Navigator.pop(context);
    },
  );
}

方案2:传入符合泛型要求的参数

如果需要返回字符串类型结果(哪怕是空内容),可以传入空字符串满足类型要求:

@override
Widget buildLeading(BuildContext context) {
  return IconButton(
    icon: const BackButtonIcon(),
    color: Theme.of(context).primaryColor,
    onPressed: () {
      close(context, '');
    },
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:25:34