You are currently viewing Dart Null Coalescing Operator

Dart Null Coalescing Operator

Imagine writing Dart code without constantly worrying about null references. Sounds dreamy, right? Well, fear not! The null coalescing operator (??) has landed, providing a safe and elegant way to deal with nullable values. Get ready to say goodbye to tedious null checks and embrace cleaner, more readable code.

What is the Null Coalescing Operator?

Simply put, the ?? operator lets you define a fallback value in case the left-hand side expression evaluates to null. It acts like a condensed conditional statement, offering a more concise and efficient way to handle nulls.

Assigning Defaults to Variables

Imagine you have a variable named name that could hold someone’s name. But what if it’s empty? You don’t want your program to scream “null reference” just because someone hasn’t filled in their details yet.

This is where ?? comes in. It says: “Hey, if name is null, don’t throw a tantrum. Instead, use this alternative value I have here.” That alternative value can be anything you like, a string, a number, or even another expression.

main() {

  String? name = null;
  String username = name ?? "Anonymous";
  
  print(username); // Output: "Anonymous"

}

In this example, the name variable is declared as nullable and is currently null. We use ?? to assign a default value (“Anonymous”) to the username variable if name is null. Otherwise, username will hold the value of name. This prevents potential errors and ensures your code continues smoothly.

?? with Functions

You can even use ?? with function calls to provide default values if the function returns null:

import 'dart:math';

int? getUserAge() {

  // Generate random number from 0 (inclusive) to 50 (exclusive)
  int intValue = Random().nextInt(50);

  // Return null if intValue is less than 20
  if(intValue < 20) return null;

  // Else return the value pointed to by intValue
  return intValue;

}

main() {

  int? age = getUserAge() ?? 0;

  print(age); // Output: 0

}

If getUserAge() returns null, the age is set to 0. Otherwise, it’s set to the generated user age returned by the getUserAge() function.

Handling Optional Parameters

Suppose you have a function that accepts an optional email parameter. You want to send a welcome email if the email address is provided, but you don’t want to force users to enter one.

void sendWelcomeEmail(String name, [String? email = null]) {

  String address = email ?? "no-reply@example.com";
  print(address);
}

main() {
  
  sendWelcomeEmail("Edward"); // Output: "no-reply@example.com"
  sendWelcomeEmail("Edward", "edwardnyirendajr@gmail.com"); // Output: "edwardnyirendajr@gmail.com"
}

The ?? operator assigns “no-reply@example.com” to address if email is null, ensuring you always have an email address to use.

Chaining Null Coalescing Operators

You can chain multiple ?? operators to handle nested null values:

main() {

  String? firstName = null;
  String? lastName = null;

  String fullName = firstName ?? lastName ?? "Guest";
  
  print(fullName);

}

This checks firstName, then lastName, and finally returns “Guest” if both are null.

Conclusion

The Dart Null Coalescing Operator (??) is a powerful tool for gracefully handling null values in your code. By incorporating it into your development practices, you can write more concise, readable, and robust applications, alleviating the concerns of missing data and preventing NullPointerExceptions. Remember to use it judiciously and understand its finer points to maximize its benefits.

Leave a Reply