non_constant_map_element
The elements in a const map literal must be constant.
Description
#The analyzer produces this diagnostic when an if
element or a spread
element in a constant map isn't a constant element.
Examples
#The following code produces this diagnostic because it's attempting to spread a non-constant map:
var notConst = <int, int>{};
var map = const <int, int>{...notConst};
Similarly, the following code produces this diagnostic because the
condition in the if
element isn't a constant expression:
bool notConst = true;
var map = const <int, int>{if (notConst) 1 : 2};
Common fixes
#If the map needs to be a constant map, then make the elements constants. In the spread example, you might do that by making the collection being spread a constant:
const notConst = <int, int>{};
var map = const <int, int>{...notConst};
If the map doesn't need to be a constant map, then remove the const
keyword:
bool notConst = true;
var map = <int, int>{if (notConst) 1 : 2};
除非另有说明,文档之所提及适用于 Dart 3.7.3 版本,本页面最后更新时间: 2025-05-08。 查看文档源码 或者 报告页面问题。