I wanted to get simplest definition for Null-aware operators in Flutter with their use cases. and also which one we can use safely as per our use cases. Please try to explain the key features Null-aware operators in Flutter.
I wanted to get simplest definition for Null-aware operators in Flutter with their use cases. and also which one we can use safely as per our use cases. Please try to explain the key features Null-aware operators in Flutter.
! is bang operator which is used to cast away nullability.
? is used to declare a property nullable.
?? is used to get the value from a variable if it is non-null or get the other value.
All examples:
int? i = 42;
print(i!.iEven); // true
int j = i ?? 0; // j = 42
! use when we are 100 present sure a variable have value.
? use when we are not sure our variable have value.
?? use for conditional situation. For example you have this condition :
if(x == null){
Text('somValue');
}else {
Text(x);
}
we can put it this way:
Text(x ?? 'somValue');
Let me tell you the difference b/w themby examples.
? is used when you've a nullable value.
Ex:List<int>? listOfInt;
if I do try to print list[0] or list.first, it'll give me an error coz the list is nullable and the property after . will only work when the list is non-nullable. Hence we've to use ? like: list?[0] or list?.first to make sure that it'll proceed further after the . if the list is non-nullable.
print(listOfInt?.first?.toString());
! is used when the value is defined nullable but you're sure that the value is not null.
Ex:List<int>? listOfInt = [0, 1];
if(listOfInt == null) print('listOfInt is null');
print(listOfInt!.first.toString());
?? is a conditional operator used when the value is null use another value instaed.
Ex:List<int>? listOfInt = [0, 1];
print(listOfInt?.first?.toString() ?? '0');