Home > front end >  Confusion with Null safety
Confusion with Null safety

Time:10-29

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 ;

CodePudding user response:

Try this:

i = i!   1

int? can be int or null and for last doesn't define increment operation.

Github thread: Nullable compound assignments are inconvenient.

Lang spec: Dart Null-Asserting Composite Assignment

CodePudding user response:

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

  • Related