4 min read

In application development (or rather software development in general), you teach machines (hardware) on how to execute a process based on various conditions written in an if-else statement. While developing a Flutter app, it’s easy to write an if-else statement in method or function. But you must have come across a situation where you need to write the if-else statement inside your widget. Right? So in this tutorial, we’ll see 3 ways to use if else statement in Flutter widget.

Here’s what we’ll cover:

The Problem

Writing the if-else statement in method or function seems to be no difficult task. But when you try to use the if-else statement directly in your widget, Flutter gives you the error. 

problem with if else statement in flutter widget

Unfortunately, you can’t write if statement inside your widget as if you were writing in your method or function. But there are a few ways you can write a conditional statement inside your widget. Let’s see them.

Ways to Use If Else Statement in Flutter Widget

There are main three ways you can include the conditional statement in your widget. 

Here they are:

  1. Using the Ternary Operator
  2. Using the Spread Operator
  3. Using the Method

You can use any of these to write an if else statement in Flutter widget based on your requirement.

Using the Ternary Operator

A ternary operator takes three operands. The first one is a condition, the second is the expression if the condition is true, and the third one is the expression if the condition is false.

It looks like this:

(age > 18) ? 'Eligible for license' : 'Not eligible'

The above code simply tells that, if a user’s age is above 18, he/she is eligible for a license otherwise not.

We can use a similar approach in the Fluter code to display the widgets based on a condition. Let’s see how.

Example:

Center(
    child: isLiked
        ? Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: const [
              Text(
                '12',
                style: TextStyle(fontSize: 120),
              ),
              Icon(
                Icons.thumb_up,
                size: 180,
                color: Color(0xff6ae792),
              ),
            ],
          )
        : const Icon(
            Icons.thumb_up,
            size: 200,
            color: Colors.black,
          ))

In the code above, if a post has any likes, it will show the likes count with a button to like. Otherwise just a like button.

Output:

if else statement in flutter widget with ternary operator

When to use:

Prefer to use the ternary operator only when you need to check a single condition. You should avoid nesting the ternary operator and use the method to write multiple if-else statements. This will generate more clearer code.

Using the Spread Operator

The spread operator (…) is used to insert multiple values into a Collection. It was introduced in Dart 2.3. The spread operator must be inside the collection widget like Column, Row, etc.

Using the spread operator for writing an if-else statement looks like this:

[
  if (age > 18) ...[
    // show license
  ] else ...[
    // show error message
  ]
]

The above code shows the license only if the user’s age is above 18.

Example 1:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    if (isShowComment) ...[
      const Icon(
        Icons.comment,
        size: 200,
        color: Color(0xff6ae792),
      )
    ] else ...[
      const Icon(
        Icons.comment,
        size: 100,
        color: Colors.black,
      )
    ]
  ],
)

Inside the Column widget, we are showing the comment icon if the isShowComment variable is true. Otherwise, we show another widget.

Example 2:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    const Icon(
      Icons.thumb_up,
      size: 100,
      color: Colors.black,
    ),
    if (isShowComment) ...[
      const Icon(
        Icons.comment,
        size: 200,
        color: Color(0xff6ae792),
      )
    ]
  ],
)

This is another use case where we are showing multiple widgets in a column. We decide to show a comment widget (with a Like widget) only if the isShowComment is true.

Example 3:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    if (isShowComment) ...[
      const Icon(
        Icons.comment,
        size: 200,
        color: Color(0xff6ae792),
      )
    ] else if (isShowLike) ...[
      //Your widget
    ] else ...[
      //Your widget
    ]
  ],
)

You can also use the spread operator to write multiple if-else statements as shown in the above code.

Output:

if else statement in flutter widget with spread operator

When to use:

Prefer to use the spread operator to write conditional statements if your child is inside the collection like Column and Row. 

Using the Method

Using a method to write an if-else statement is the go-to way if none of the above methods works for you. Writing a condition statement in a method produces clearer code.

Example:

Center(
  child: getLockStatus(),
)
Widget getLockStatus() {
  if (isLocked) {
    return const Icon(
      Icons.lock_outline,
      size: 200,
      color: Color(0xff6ae792),
    );
  } else {
    return const Icon(
      Icons.lock_open,
      size: 200,
      color: Colors.black,
    );
  }
}

The if-else statement with a widget (to be returned) is moved to a dedicated method. The method returns the widget based on the condition return inside. 

Output:

if else statement in flutter widget using method

When to use:

Writing a conditional statement inside the method is preferable if you would like to produce clean code and none of the other options work for you.

Thanks!

Conclusion

In this tutorial, we’ve explored the three ways of writing an if else statement in Flutter widget with a practical example. We also learned when to use each of them based on your requirement.

Would you like to check other interesting Flutter tutorials?