Reputation:
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. But I am getting an error in the operator part (<=). Can you help fix it?
Upvotes: 0
Views: 174
Reputation: 782
To expand on Sabahat's answer these are null safe operators in Dart.
sensorver?.leftMotorSpeed
basically means 'give me the value of leftMotorSpeed
if sensorver
is not null'.
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. This is dart's way of trying to ensure you don't encounter exceptions at runtime due to a null value.
There are two ways you can deal with this.
Dangerous option: Tell Dart you know sensorver
is definitely not null (Sabahat's answer).
You can tell dart you know for certain sensorver
is not null with the !
operator. This is basically telling Dart 'shut up with you warnings, I know this will never be null'. Thus Sabahat's answer of color: sensorver!.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
will work.
However if sensorver
is ever null it will cause your entire program to crash
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. 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
. However if sensorver
is null, it will provide you with the fallback value of 0
. The fallback value can be anything you like, as long as it's guaranteed to not be null.
Upvotes: 3
Reputation: 257
You need to check fist sensorver is null or not as below:
color: sensorver!=null&&sensorver!.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
Upvotes: 1
Reputation: 1364
check this
color: sensorver!.leftMotorSpeed <= 50 ? Colors.amber : Colors.red,
Upvotes: 0