Home > Back-end >  Nullable datatype check doesn't work with string interpolation
Nullable datatype check doesn't work with string interpolation

Time:06-12

The following code is valid in Dart 2.12.4:

String? firstName, lastName;

firstName = 'John';

bool firstNameIsNullableString = firstName is String?; // true
bool lastNameIsNullableString = lastName is String?; // true
bool firstNameIsString = firstName is String; // true
bool lastNameIsString = lastName is String; // false

When I try to run the same expression in string interpolation via ${}, it throws the error:

print('firstName is of type: String? ${firstName is String?}');
file.dart:7:62: Error: Expected an identifier, but got '}'.
Try inserting an identifier before '}'.
  print('firstName is of type: Stirng? ${firstName is String?}');

CodePudding user response:

Your first affirmation is wrong (at least on dart 1.17.1) Run your code on dartpad.dev and see for yourself.

Missing brackets so your last code is understandable by the analyzer. It was processing it as the ternary operator probably.

void main() {
  String? firstName, lastName;

  firstName = 'John';

  bool firstNameIsNullableString = firstName is String?; // true
  bool lastNameIsNullableString = lastName is String?; // true
  
  print(firstNameIsNullableString);
  print(lastNameIsNullableString);

  //Missing brackets here
  print('firstName is of type: String? ${(firstName is String?)}'); 
}
  • Related