[英]I am getting error in dart operator operation
color:sensorver?.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
I want to change color using above code.我想用上面的代码改变颜色。 If the incoming data is less than 50, I want to make it red if not amber.如果传入的数据小于 50,如果不是琥珀色,我想将其设为红色。 But I am getting an error in the operator part (<=).但是我在运算符部分(<=)中遇到错误。 Can you help fix it?你能帮忙修一下吗?
check this检查这个
color: sensorver!.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
You need to check fist sensorver is null or not as below:您需要检查第一个传感器是 null 或不是如下:
color: sensorver!=null&&sensorver!.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
To expand on Sabahat's answer these are null safe operators in Dart .为了扩展 Sabahat 的答案,这些是 Dart 中的null 安全运算符。
sensorver?.leftMotorSpeed
basically means 'give me the value of leftMotorSpeed
if sensorver
is not null. sensorver?.leftMotorSpeed
基本上意味着'如果sensorver
不是 null,请给我leftMotorSpeed
的值。
Therefore you get an error when trying to see if it's less than or equal to 50 since you can't compare something that might be null to the number 50, which is definitely not null.因此,当您尝试查看它是否小于或等于 50 时会出现错误,因为您无法将可能是 null 的东西与数字 50 进行比较,这绝对不是 null。 This is dart's way of trying to ensure you don't encounter exceptions at runtime due to a null value.这是 dart 试图确保您在运行时不会因为 null 值而遇到异常的方式。
There are two ways you can deal with this.有两种方法可以处理这个问题。
Dangerous option : Tell Dart you know sensorver
is definitely not null (Sabahat's answer).危险选项:告诉 Dart 你知道sensorver
绝对不是 null (沙巴的回答)。
You can tell dart you know for certain sensorver
is not null with the !
你可以告诉 dart 你知道某些sensorver
不是 null 与!
operator.操作员。 This is basically telling Dart 'shut up with you warnings, I know this will never be null'.这基本上是在告诉 Dart '闭嘴警告,我知道这永远不会为空'。 Thus Sabahat's answer of color: sensorver.?leftMotorSpeed <= 50. Colors:amber. Colors,red,
因此,Sabahat 对color: sensorver.?leftMotorSpeed <= 50. Colors:amber. Colors,red,
color: sensorver.?leftMotorSpeed <= 50. Colors:amber. Colors,red,
will work. color: sensorver.?leftMotorSpeed <= 50. Colors:amber. Colors,red,
将工作。
However if sensorver
ever is null it will cause your entire program to crash但是,如果sensorver
曾经是 null 它将导致您的整个程序崩溃
Safe option : Provide a fallback value.安全选项:提供后备值。
If sensorver
could be null the safe option is to provide a fallback value that dart will use in the case it is null.如果sensorver
可以是 null,则安全选项是提供 dart 将在 null 的情况下使用的备用值。 This can be accomplished with the ??
这可以通过??
operator.操作员。 For example:例如:
color: sensorver?.leftMotorSpeed?? 0 <= 50? Colors.amber: Colors.red,
This means that if sensorver
is not null it will provide you the value of leftMotorSpeed
.这意味着如果sensorver
不是 null 它将为您提供leftMotorSpeed
的值。 However if sensorver
is null, it will provide you with the fallback value of 0
.但是,如果sensorver
是 null,它将为您提供后备值0
。 The fallback value can be anything you like, as long as it's guaranteed to not be null.备用值可以是您喜欢的任何值,只要保证它不是 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.