What operators exist in Null-safety?
sobes.tech AI
Answer from AI
In Null Safety in Flutter, the following operators related to nullable types are used:
-
?(Question Mark): Declares a variable as nullable.String? nullableString; // Variable can contain String or null -
!(Bang Operator / Non-nullable Assertion): Guarantees to the compiler that the value is notnullat this moment. Use with caution, as it can cause a runtime error if the value turns out to benull.String nonNullableString = nullableString!; // Guarantee that nullableString is not null -
??(Null Coalescing Operator): Provides a fallback value if the left side of the expression isnull.String result = nullableString ?? "Default Value"; // If nullableString is null, result will be "Default Value" -
??=(Null Coalescing Assignment Operator): Assigns the value on the right to the variable only if the left side isnull.String? variable; variable ??= "Initial Value"; // If variable is null, assign "Initial Value" -
?.(Null-aware Access Operator): Allows safe access to members of an object that may benull. If the object isnull, the expression returnsnull.String? nullableString; int? length = nullableString?.length; // If nullableString is null, length will be null -
?[](Null-aware Index Operator): Allows safe access to list elements or Map entries that may benull. If the list or Map isnull, the expression returnsnull.List<int>? nullableList; int? firstElement = nullableList?[0]; // If nullableList is null, firstElement will be null