Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten code when I do a variable assignment in a condition in Dart?

Here's the ugly long code:

var i;
if(true)
  i = 1;
else
  i = 0;

When I try this:

var i = (true ? 0 : 1);

it doesn't work resulting in an error on the following line. I guess I was a bit inattentive reading Dart's syntax specs, so can anybody show me the right way?

like image 949
snitko Avatar asked Jan 16 '14 07:01

snitko


People also ask

Can't be used as a setter because it's final?

This error happened because the text property of the TestModel class is final. Final objects arent meant to be changed in Flutter. to fix this problem you should go to the TestModel class and remove final from the text property.


1 Answers

This looks perfectly fine from a syntax point of view. You can omit the parentheses.

I get a warning 'Dead code' at '1' with your example because of 'true'.
The Darteditor shows you a hint that you wrote code that may contain a bug because he knows your expression can never evaluate to 1 because of the hardcoded 'true'.

void main(List<String> args) {
    var b = true;
    var i = b ? 0 : 1;
}

doesn't produce a warning.

like image 96
Günter Zöchbauer Avatar answered Nov 03 '22 00:11

Günter Zöchbauer