Null-aware Operator Examples in Dart and Flutter

Null-aware operators are a new feature in the Flutter framework that allows you to call functions and pass arguments without checking for null. Null-aware operators allow developers to write cleaner, more concise code. In Dart and Flutter, there are four null-aware operators which allow you to check for null and take different actions based on whether or not a variable is null.

These operators are particularly useful when working with data that may or may not be null. For example, if you are retrieving data from a remote source, there is a chance that the data may not be available, in which case you would want to use the ?? operator to provide a default value.

  • ?. – This operator returns null if the variable is null, otherwise, it returns its value.
  • ?? – It returns a default value if the variable is null.
  • ??= – This operator is used to assign values to the variables that can be null.
  • …? – It checks if the list is null or not and carries out the operation accordingly.
List<int>? numberList = null;
print(numberList?.length); //null
List<int>? numberList = [1243, 34521, 943765];
print(numberList?.length); //3

String? productName;
print(productName ?? 'Phone'); //Phone
String? productName = "Crystal Ring";
print(productName ?? 'Phone'); //Crystal Ring

String? brand;
brand ??= 'Samsung';
print(brand); //Samsung

List<int>? brands;
print([...?brands, 'Apple']); //Apple

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.