Dart中如何将Map值设为函数可选参数的常量默认值?
Dart 可选参数默认值为Map取值的报错解决方案
报错原因
The default value of an optional parameter must be constant
Dart语法规定可选参数的默认值必须是编译期常量,而toastDuration["default"]属于运行时才能计算结果的表达式,哪怕给toastDuration加const修饰,下标访问的返回值也不属于编译期常量,因此直接赋值会报错。
解决方案
方案1:抽离公共常量(推荐,性能最优)
把默认时长抽成顶层编译期常量,同时给Map和参数默认值使用,既保证取值统一,又符合语法要求:
// 抽离公共常量 const int defaultToastDuration = 4000; Map<String, int> toastDuration = { "default": defaultToastDuration, }; void showToast({ required BuildContext context, required String msg, int msDuration = defaultToastDuration, // 直接用常量作为默认值 bool hidePrev = true, }) { // 业务逻辑 }
方案2:用null作为中转(适合Map会动态修改的场景)
如果你的toastDuration运行时可能会变更值,可以把参数声明为可空类型,函数内部再赋值默认值:
Map<String, int> toastDuration = { "default": 4000, }; void showToast({ required BuildContext context, required String msg, int? msDuration, // 不设默认值,默认为null bool hidePrev = true, }) { // 函数内部判断赋值,运行时读取Map的最新值 msDuration ??= toastDuration["default"]!; // 业务逻辑 }
额外提示
你原代码里Map的key拼写为defaut(少了字母l),和后续取值的default不一致,也会导致运行时取到null,建议修正拼写。
内容的提问来源于stack exchange,提问作者aWebDeveloper
相关产品推荐
相关产品推荐

