Sobes.tech
Middle

What features have been introduced with the implementation of Null-safety in Dart?

sobes.tech AI

Answer from AI

With the introduction of Null-safety in Dart, the following features appeared:

  • Absence of runtime errors related to null: The compiler guarantees that a variable declared as non-nullable will never have a null value. This eliminates NoSuchMethodError errors at runtime, which could previously occur when calling a method on a null value.
  • Explicit indication of null possibility: Now it is necessary to explicitly specify whether a variable can have a null value by adding ? to the type.
    String? nullableString; // Can be null
    String nonNullableString = "Some value"; // Cannot be null
    
  • Improved readability and predictability of code: The code becomes more understandable, as it is immediately clear which variables are guaranteed not to be null.
  • Performance optimization: The compiler can use nullability information for more efficient code compilation.
  • Operators for safe null handling: New operators have appeared:
    • ?. (null-aware access): Calls a method or accesses a property only if the object is not null.
      String? nullableString = getPotentiallyNullString();
      int? length = nullableString?.length; // length will be null if nullableString is null
      
    • ?? (null-aware assignment): Assigns a value only if the variable is null.
      String? nullable;
      String nonnull = nullable ?? "default"; // nonnull will be "default"
      
    • ??= (null-aware assignment): Assigns a value to the variable only if it is null.
      String? text;
      text ??= "hello"; // text will become "hello"
      
    • ! (non-null assertion): Asserts that the value is not null. Use with caution, when the developer is sure that the value is not null, but the compiler cannot guarantee this.
      String? nullableValue;
      // ... (logic that guarantees nullableValue is not null)
      String nonNullable = nullableValue!; // Assert that it is not null
      
  • late type: Allows deferring the initialization of a non-nullable variable until the first access.
    late String initializedLater;
    
    void setup() {
      initializedLater = "Initialized!";
    }
    
  • required type: Used in constructors and functions to specify mandatory parameters. In the context of null-safety, required makes parameters non-nullable by default (if the type is not marked with ?).
    class MyClass {
      MyClass({required String name});
    }