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

Flutter自定义SnackBar报错:如何正确传递snackMessage参数?

解决CustomSnackBar中snackMessage参数传递错误的问题

错误提示Arguments of a constant creation must be constant expressions的核心原因是:你给Center和Text组件添加了const关键字,但snackMessage是CustomSnackBar的实例参数,属于运行时动态值,并非编译期常量,不符合const构造的要求。

修正方法很简单,去掉Center和Text前的const关键字即可。如果想保留局部常量优化,可以只给TextStyle保留const(因为它的参数都是固定常量):

import 'package:flutter/material.dart';

class CustomSnackBar extends StatelessWidget {
  final String snackMessage;
  final Color snackColor;

  const CustomSnackBar(
      {super.key, required this.snackMessage, required this.snackColor});

  @override
  Widget build(BuildContext context) => SnackBar(
        content: Center(
          child: Text(
            snackMessage,
            style: const TextStyle(color: Colors.black, fontWeight: FontWeight.w900),
          ),
        ),
        behavior: SnackBarBehavior.floating,
        margin: EdgeInsets.only(
          bottom: MediaQuery.of(context).size.height - 100,
          left: 10,
          right: 10,
        ),
        backgroundColor: snackColor,
      );
}

这样修改后,snackMessage就能正常传递并显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:22:42