跳到主要內容

constant_pattern_with_non_constant_expression

常量模式的表示式必須是有效的常量。

描述

#

當常量模式的表示式不是有效的常量時,分析器會生成此診斷資訊。

示例

#

以下程式碼會生成此診斷資訊,因為常量模式 i 不是常量

dart
void f(int e, int i) {
  switch (e) {
    case i:
      break;
  }
}

常見修復方法

#

如果需要匹配的值已知,則將表示式替換為常量

dart
void f(int e, int i) {
  switch (e) {
    case 0:
      break;
  }
}

如果需要匹配的值未知,則重寫程式碼,不使用模式

dart
void f(int e, int i) {
  if (e == i) {}
}