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

