-4

I'm pretty new to flutter and because of the null safety feature I've been getting a lot of errors from a code that will run perfectly fine in Java or other langs. For example this-

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++;

Logic
  • 53
  • 1
  • 9
  • 3
    What is `i++` supposed to do on the first iteration of the loop? Make `i` non-nullable and initialize it first: `int i = 0;`. – jamesdlin Oct 28 '21 at 21:46

1 Answers1

-2

You can't do either i++ or i+=1 on a nullable variable, because the reason is simple, null variable can have null values which will make increment no sense.

In addition to this, you can't even do i!++ or i!+=1 even if you are sure that i is not null. There is an open issue for this https://github.com/dart-lang/language/issues/1113

So for now you can do this i = i! + 1

Update: For i = i! + 1 to work you need to be sure about i not being null. So it's better to initialise/assign i with some value before using it.

Ronak Jain
  • 159
  • 1
  • 7
  • 3
    `i = i! + 1` won't work because `i` is never initialized to a non-null value, and it therefore will throw an exception on the first iteration. The better fix in this case is to initialize `i` to a non-null value. – jamesdlin Oct 28 '21 at 21:48
  • @jamesdlin thanks for your input. Answer updated. – Ronak Jain Oct 29 '21 at 20:56