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

Flutter报错‘This expression has a type of 'void' so its value can't be used’如何解决?

解决Flutter错误:This expression has a type of 'void' so its value can't be used

错误出现在_submitExpenseData方法的这行代码里:

widget.onAddExpense(
  Navigator.of(context).pop(Expense(
    title: _titleController.text,
    amount: enterAmount!,
    date: _selectedDate!,
    category: _selectedCategory)));

问题根源

Navigator.pop()的返回类型是void,它仅负责关闭当前路由,没有任何返回值。但你现在把pop()的调用结果直接传给了widget.onAddExpense()——而onAddExpense要求的参数是Expense类型,这就造成了类型不匹配:你试图把一个void类型的值当作Expense对象来使用,触发了这个错误。

修复代码

把逻辑拆成两步执行:先创建Expense对象并传递给回调,再调用pop关闭页面:

// 1. 先构造Expense对象并传给回调函数
final newExpense = Expense(
  title: _titleController.text,
  amount: enterAmount!,
  date: _selectedDate!,
  category: _selectedCategory,
);
widget.onAddExpense(newExpense);

// 2. 单独调用pop关闭当前页面
Navigator.of(context).pop();

对应官方提示的验证

  • API使用正确性:你错误地将Navigator.pop()(无返回值)当作有返回值的函数来传递参数,pop的正确用法是单独执行关闭操作,而非用来返回数据。
  • 类型参数/变量检查:onAddExpense的参数类型明确是Expense,修正后确保了传入的参数类型完全匹配,避免了void类型的误用。

内容的提问来源于stack exchange,提问作者Dinesh Kumar M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:05:27