Skip to main content

Operators ?? & ?

Dart has two operators that can simplify the use of if-else:

  1. The ternary operator: ?
  2. If null operator: ??

Let's see how they work:

The ternary operator: ?

condition ? result1 : result2 if condition is true evaluates result1 but if condition is false evaluates result2. Let's take a look at the following example with if-else:

var age = 17;

if (age >= 18) {
print('Adult');
} else {
print('Kid');
}

Now, let's use the ternary operator instead of if-else:

var age = 17;

age >=18 ? print('Adult') : print('Kid');

Or, if you prefer, we can assign the result to a variable. Like this:

var age = 17;

String result = age >= 18 ? 'Adult' : 'Kid';
print(result)

As you can see, using the ternary operator produces the same result as if-else.

If null operator: ??

result1 ?? result2 if result1 is not null then evaluates result1 otherwise evaluates result2. Let's take a look at the following example using if-else:

String? name = 'Yayo';

if (name == null) {
print('name is null');
} else {
print(name);
}

Let's use the if null operator instead of if-else:

String? name = 'Yayo';

print( name ?? 'name is null' );

The previous code will print Yayo because name is not null. If you change the value of name to null, then the right side of the operator is evaluated, and it will print name is null.

Let's run some examples in DartPad: