Site icon TestingDocs.com

Dart Conditional Operators

Overview

Dart conditional operators are used to perform conditional operations on the operands and assignments. These operators enable you to write concise and readable code for making decisions based on certain conditions.

Dart Conditional Operators

The conditional operator is also known as the ternary operator. This operator allows you to evaluate a condition and return a value based on the result.

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, if 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

 

 

Exit mobile version