Dart Conditional Operators
Dart Conditional Operators
Dart conditional operators perform conditional operations on operands and assignments. These operators enable you to write concise and readable code for making decisions based on certain conditions.
The conditional operator, also known as the ternary operator, allows you to evaluate a condition and return a value based on the result.
Syntax
It has the following syntax:
condition ? expression1: expression2
It is like an if-else statement. If the condition is true, then expression1 is evaluated and returned, else expression2 is evaluated and returned.
Null-aware operator
It has the following syntax:
expression ?? expression2
If expression1 is non-null, it returns its value; otherwise, it returns expression2 value.
Example
Let’s look at some examples.
/* * Conditional Operators demo Dart Program * Dart Tutorials - www.TestingDocs.com */ void main() { int a = 9; //conditional Statement var result = (a < 0) ? "A is Negative" : "A is Positive or Zero"; print(result); // Null aware conditional statement var foo; var out = foo ?? "foo is Null"; print(out); // Assign value to foo foo = 1000; out = foo ?? "foo is Null"; print(out); }
Output
A is Positive or Zero
foo is Null
1000
—