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
相关产品推荐
相关产品推荐

