Flutter调用onTap函数报错:Not a constant expression 求解决方案
解决“Not a constant expression”错误
错误根源:你给MyButton的构造函数加了const修饰,但传递的onTap参数是一个匿名函数((){Navigator.pushNamed(context,'/menupage');}),匿名函数不属于常量表达式,不符合const构造函数对参数的要求(const构造要求所有参数必须是编译期可确定的常量)。
解决步骤:
- 修改
button.dart里的MyButton构造函数,去掉const关键字:
class MyButton extends StatelessWidget { final String text; final void Function()? onTap; // 去掉const,改成普通构造函数 MyButton({super.key, required this.text, required this.onTap,}); @override Widget build(BuildContext context){ return GestureDetector( onTap: onTap, child: Container( decoration: BoxDecoration(color: Colors.white,), padding: EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( text, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), ), ], ), ), ); } }
另外顺便修正了代码里的几个小问题:
Color.white改为Colors.white(Dart中颜色常量在Colors类下)- 补全了
Row组件mainAxisAlignment行末尾的逗号 - 将文字颜色改为黑色(原代码背景和文字都是白色,会导致文字不可见)
内容的提问来源于stack exchange,提问作者newtocode19
相关产品推荐
相关产品推荐

