【发布时间】:2021-09-28 07:46:51
【问题描述】:
我是 Dart 新手,希望有人能解释这个变量范围警告。
当我使用以下内容时:
enum fruits {tomatoes, apples, oranges}
void main() {
for (var item in fruits.values) {
var color = 'red'; // Local variable 'color' declared
switch (item){
case fruits.apples:
break;
case fruits.tomatoes:
break;
default:
color = 'orange'; // Local variable 'color' used, analyzer doesn't see
break;}
print (color); // Local variable 'color' used, analyzer sees
}
}
代码分析器上面没有问题。但是,如果我注释掉打印语句// print (color);,我会从分析器中收到警告The value of the local variable 'color' isn't used.,即使color 用于switch 语句的默认情况。
为什么分析器没有“看到”default 案例中的局部变量?
【问题讨论】:
-
给变量赋值并不意味着使用它。它不会对任何进一步的计算做出贡献,因此它是无用的,因此分析器会告诉你。
标签: flutter dart switch-statement local-variables analyzer