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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:04:53