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};