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

Flutter中传递VoidCallback给Widget时出现‘Invalid constant value’错误,如何解决?

问题原因

你给SingleChildScrollView、Column以及ProfileMenu都加了const修饰,但传入的匿名回调函数() { print('a'); }属于运行时生成的对象,不是编译时常量。Flutter要求常量Widget的所有参数必须是编译时常量,因此触发了"Invalid constant value"错误。

解决方法

移除那些包含非常量参数的Widget前面的const关键字即可,具体修改后的代码如下:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: const AppBar(
      title: const Text("Profile"),
      centerTitle: true,
    ),
    body: SingleChildScrollView(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: Column(
        children: [
          ProfileMenu(
            text: "Profile",
            icon: "assets/icons/Profile Icon.svg",
            press: () {
              print('a');
            }
          ),
          const SizedBox(height: 16), // 这个Widget参数都是常量,可保留const
          ProfileMenu(
            text: "Account",
            icon: "assets/icons/Account Icon.svg",
            press: () {
              print("b");
            }
          ),
        ],
      ),
    ),
  );
}

补充:像SizedBox(height:16)这类所有参数都是常量的Widget,依然可以保留const修饰,不影响性能优化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:32:41