You need to enable JavaScript to run this app. Flutter报错:命名参数未定义,如何解决类间传值问题?
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错:命名参数未定义,如何解决类间传值问题?

Flutter传递参数报错:The named parameter isn't defined 解决方法

我想把int值10从tmpWidget类传递到CakeTimerUI类,编写了如下代码,但出现「The named parameter isn't defined.[flutter]」错误,请问该如何解决?

CakeTimerUI代码

class CakeTimerUI extends StatefulWidget {
  final int value2;

  const CakeTimerUI({super.key, required this.value2});

  @override
  CakeTimerState createState() => CakeTimerState();
}

class CakeTimerState extends State<CakeTimerUI> {
  @override
  Widget build(BuildContext context) {
    return const Center(
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TimerFunction(),
          ],
        ),
      ),
    );
  }
}

tmpWidget代码

class tmpWidget extends StatelessWidget {
  final int value1;

  const tmpWidget({super.key, required this.value1});

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQueryData = MediaQuery.of(context);
    double screenWidth = mediaQueryData.size.width;
    double screenHeight = mediaQueryData.size.height;
    return Container(
      width: screenWidth / 3 - screenWidth * 0.01,
      height: screenHeight / 2 - screenWidth * 0.01,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: Colors.lightGreen,
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const CakeTimerUI(value2: 10),
          Text('Value: $value1', style: const TextStyle(fontSize: 16)),
        ],
      ),
    );
  }
}

错误原因及解决方法

错误根源是你给CakeTimerUI实例加了const修饰符,但const构造要求所有参数必须是编译时常量——你的super.key默认是null(非常量),导致const上下文不成立,编译器误报参数未定义。

最直接的解决方式:

  • 去掉CakeTimerUI前的const,修改后的代码:
    CakeTimerUI(value2: 10),
    

如果你的需求是把tmpWidget的value1传递给CakeTimerUI(而非硬写10),则改成:

CakeTimerUI(value2: value1),

若确实需要使用const构造,需给key参数传递常量值,比如:

const CakeTimerUI(key: const Key('cake_timer'), value2: 10),

但实际开发中这类UI组件没必要强制用const,去掉const是最简洁的解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:00:27