Junior
What is null safety in Dart?
sobes.tech AI
Answer from AI
Null safety is a system in Dart that helps prevent runtime errors related to null dereferencing. The compiler analyzes the code and determines whether a variable can hold a null value. If a variable is declared as non-nullable, the compiler guarantees that it will never be assigned null.
Main aspects of null safety:
- Implicit non-nullable type: By default, types do not allow null (non-nullable).
// int cannot be null int count = 0; - Nullable type: To explicitly indicate that a variable can be null, a question mark
?is used:// String? can be null String? name; !operator (non-null assertion): Used to assert that a nullable expression is not null. Use with caution, as it throws an exception if null.String? nullableName = 'Flutter'; // Using !, knowing that nullableName is not null in this context print(nullableName!.length);?operator (null-aware operators): Used for safe access to members or method calls on nullable expressions.?.(null-aware access):String? nullableString; // If nullableString is not null, length is called; otherwise, result is null int? length = nullableString?.length;??(if null):String? serverName; // If serverName is not null, its value is used; otherwise, 'Guest' String displayName = serverName ?? 'Guest';??=(if null assign):String? cache; // If cache is null, assign 'Loading...' cache ??= 'Loading...';
- Flow Analysis: Dart compiler analyzes the code and determines when a nullable variable is guaranteed not to be null in a certain part of the code, allowing it to be used as non-nullable.
String? greeting = getGreeting(); // The compiler knows that greeting is not null after this check if (greeting != null) { print(greeting.toUpperCase()); // Safe to use toUpperCase() }
Advantages of null safety:
- Error reduction: Prevents NullReferenceException (or similar) at runtime.
- Improved readability: Clearly indicates whether a variable can be null.
- Increased performance: The compiler can perform optimizations knowing which variables are guaranteed not to be null.
Null safety was introduced in Dart 2.12.