Home > Mobile >  Error: Operator '[]' cannot be called on 'String?' because it is potentially nul
Error: Operator '[]' cannot be called on 'String?' because it is potentially nul

Time:12-13

main() {
    String? variable1=stdin.readLineSync();
    String? variable2=variable1[0]; // Error: Operator '[]' cannot be called on 'String?' because it is potentially null.
}

Why do I need to add null check when variable2 is already null safe? I know how to correct this, please explain why is this happening.

CodePudding user response:

variable1 is nullable. I believe this has to do with the fact that readLineSync returns null if no input is passed. Anyway...

If variable1 is nullable, this means it could be null. Reading null[0] throws an error, this is why variable2 needs a null check.

You say you already know how to fix this, I will add the solution here anyway in case anyone else sees this answer and needs a solution.

String? variable1=stdin.readLineSync();
String? variable2=variable1?[0];
String variable3='';
if (variable1 != null) {
  variable3 = variable1![0];
}
String variable4 = variable1?[0] ?? 'default';

Above, variable2 will be null if and only if variable1 is null, variable3 will never be null, but if variable1 is null, it will be '', likewise, variable4 will be 'default' if variable1 is null

  •  Tags:  
  • dart
  • Related