我是一个新手,因为null安全特性,我从一个在Java或其他语言中运行得很好的代码中得到了很多错误。例如-
int ? i;
var icecreamFlavours = ['chocolate', 'vanilla', 'orange'];
icecreamFlavours.forEach((item) {
i++; //This is where I get the error
print('We have the $item flavour');
});
My Error Message
Error: Operator '+' cannot be called on 'int?' because it is potentially null.
i++;
Error: A value of type 'num' can't be assigned to a variable of type 'int?'.
i++;
你不能在一个空变量上做i++
或i+=1
,因为原因很简单,空变量可以有空值,这将使增量没有意义。
除此之外,即使你确定i
不为空,你甚至不能执行i!++
或i!+=1
。这是一个开放的问题https://github.com/dart-lang/language/issues/1113
现在你可以输入i = i! + 1
更新:要使i = i! + 1
工作,您需要确保i
不为空。因此,最好在使用i
之前初始化/分配一些值。