Ternary Operation in flutter dart

Hi Guys, Welcome to Proto Coders Point, This dart/flutter article is on Conditional operator (i.e. Ternary Operation in flutter dart).

Video Tutorial


What is ternary operator with example

In Flutter Dart, We can use Conditional operator in two ways: One is using normal if/else condition statement & another is ternary operator in flutter dart.

Ternary Operator dart takes three operands:

  • A Condition followed by (?) question marks.
  • Then a experssion that execute when condition is true, followed by (:) colon.
  • Then finally a expression that execute when condition is false.

Syntax of Ternary operation in flutter

condition ? if True : if False

Ternary Operation Example

void main(){
  
int num = 10; //init

bool val = (num<=9) ? true : false; // check condition using ternart operations
  
print(val); // return false : as number is > 9
  
}

Nested conditional Operation using Ternary Operation

In dart ternary is right associative, that means it can used to as nested if/else condition like a chains.

flutter cascade operator ( .. ) n...
flutter cascade operator ( .. ) notation
Example:

condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : condition4 ? value4
         : condition5 ? value5
         : valueN;

Example: Nested Ternary operation in dart

void main() {
  int age = 30;
  String output = age < 1
      ? 'Infrant is Just Borned'
      : age < 4
          ? 'Baby is less then 4 Year,'
          : age < 12
              ? 'Childhood'
              : age < 18
                  ? 'Adolescence'
                  : 'Grown Up';
  print(output);
}

Example on How to use Ternary Operation in Widget building

An real time example, when and how to use Ternary Conditional Operation to show different widget in flutter depending on condition.

Eg: If Condition is true, show Image Widget else Show Error message using Text Widget.

 bool showImage = true;

Container(
              height: 300,
              width: 300,
              child: showImage ? Image.network('<Image url Here>') : CircularProgressIndicator(),
            ),
bool showImage = false;

Container(
              height: 300,
              width: 300,
              child: showImage ? Image.network('<Image url Here>') : CircularProgressIndicator(),
            ),