跳到主内容

non_constant_map_element

const map 字面量中的元素必须是常量。

描述

#

当 const map 中的 if 元素或扩展元素不是常量元素时,分析器会产生此诊断。

示例

#

以下代码会产生此诊断,因为它尝试扩展非常量 map

dart
var notConst = <int, int>{};
var map = const <int, int>{...notConst};

类似地,以下代码会产生此诊断,因为 if 元素中的条件不是常量表达式

dart
bool notConst = true;
var map = const <int, int>{if (notConst) 1 : 2};

常见修复

#

如果 map 需要是 const map,则将元素设为常量。在扩展示例中,你可以通过将正在扩展的集合设为常量来做到这一点

dart
const notConst = <int, int>{};
var map = const <int, int>{...notConst};

如果 map 不需要是 const map,则移除 const 关键字

dart
bool notConst = true;
var map = <int, int>{if (notConst) 1 : 2};