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

Flutter开发餐食APP出现NoSuchMethodError报错该如何解决?

问题原因

你存在两个核心错误导致报错和功能异常:

  • 函数调用逻辑错误
    你在_buildSwitchListTile方法中给SwitchListTile的onChanged属性赋值时,直接执行了updateValue(),这会在组件构建阶段就直接调用该函数,而非等待用户触发切换事件时执行。且onChanged需要接收一个ValueChanged<bool>类型的函数引用,你直接执行函数后返回的是void,类型不匹配就触发了参数不匹配的闭包调用错误。
  • 参数传递错误
    你在Vegetarian、Vegan两个开关的_buildSwitchListTile调用中,currentValue参数错误传入了_lactoseFree,会导致这两个开关的初始状态和点击状态都和乳糖不耐受开关绑定,功能异常。

修复步骤

1. 修复_buildSwitchListTile方法的onChanged赋值

将onChanged: updateValue()改为直接传入函数引用,同时建议显式声明函数类型避免后续类型错误:

Widget _buildSwitchListTile(
  String title,
  String description,
  bool currentValue,
  // 显式声明参数类型为ValueChanged<bool>,避免类型不匹配
  ValueChanged<bool> updateValue,
){
    return SwitchListTile(
      title: Text(title),
      value: currentValue,
      subtitle: Text(description),
      // 去掉括号,直接传函数引用,不要提前执行
      onChanged: updateValue,
    );
}

2. 修正Vegetarian、Vegan开关的参数传递

将这两个开关的currentValue参数改为对应的状态变量:

_buildSwitchListTile(
  'Vegetarian',
  'Only include Vegetarian meals',
  // 原来的_lactoseFree改为_vegetarian
  _vegetarian,
  (newValue){
    setState(() {
      _vegetarian =  newValue;
    });
  }
),
_buildSwitchListTile(
  'Vegan',
  'Only include Vegan meals',
  // 原来的_lactoseFree改为_vegan
  _vegan,
  (newValue){
    setState(() {
      _vegan =  newValue;
    });
  }
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:02