How to use ternary operator in Flutter

In the previous section, we have seen how the ternary operator works. In this section we will learn how to use it in Flutter.

Just like if-else control flow it works.

The ternary operator reduces the code line firstly. And, secondly, it enhances the readability.

Let us see, an example in Dart. Then we will implement that concept in Flutter.

void main() {
  bool johnSmithIsTheBestGunner = true;
  
  if(johnSmithIsTheBestGunner){
    print('John Smith is the best gunner.');
  } else {
    print('Hicky is the best gunner');
  } 
// output: John Smith is the best gunner. 
  
}

In the above code, the output is quite expected. The first part of if-else logic will execute when the first condition is true.

However, we can reduce this code.

void main() {
johnSmithIsTheBestGunner ? print('John Smith is the best gunner.')
  : print('Hicky is the best gunner');
} // output: John Smith is the best gunner. 

In addition, we can store the boolean value in another variable.

That variable should be, certainly, has a boolean data type. However, we can make a complex logic-tree.

void main() {
  bool johnSmithIsTheBestGunner = true;
  
  bool willJohnKillHicky = johnSmithIsTheBestGunner ? true : false;
  
  print(willJohnKillHicky); // true
  
  // now we can build a complex logic tree based on this single expression
  
  bool willPeaceReturnToJericho = willJohnKillHicky ? true : false;
  
  ((johnSmithIsTheBestGunner && willJohnKillHicky) && willPeaceReturnToJericho) ?
    print('John Smith is the best gunner. He kills Hicky and peace returns to Jericho.') :
  print('Jericho remains the ghost town.');
  
  // John Smith is the best gunner. He kills Hicky and peace returns to Jericho.  
}

This is the advantage. We can use ternary, or conditional operator and create a complex logic-tree.

With if-else, you cannot do that. You cannot assign the value of an if-else logic-tree to a variable.

Look at the code below.

We cannot do that with if-else logic. Right?

bool willJohnKillHicky = johnSmithIsTheBestGunner ? true : false;

Similarly, we can reduce the code in Flutter too.

We have built the Flutter App before, where we have changed the color of two Container Widgets.

To do that, we have used this method, and pass an enum data type as parameter.

class _MyHomePageState extends State<MyHomePage> {
  Color firstContainerColor = inactiveColor;
  Color secondContainerColor = inactiveColor;
  void _changeColor(ContainerColor selectedContainer) {
    if (selectedContainer == ContainerColor.first) {
      firstContainerColor = activeColor;
      secondContainerColor = inactiveColor;
    } else {
      firstContainerColor = inactiveColor;
    }
    if (selectedContainer == ContainerColor.second) {
      secondContainerColor = activeColor;
      firstContainerColor = inactiveColor;
    } else {
      secondContainerColor = inactiveColor;
    }
  }
...
// code is incomplete for brevity
// please visit the respective GitHub branch for full code.

And later, we have called this method and pass the first and second enum object as follows.

 child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _changeColor(ContainerColor.first);
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        color: firstContainerColor,
....
// incomplete
// please visit the respective GitHub branch for full code.

Now, the question is, can we use ternary operator instead of this method?

Ternary operator in Flutter

Let us change the code completely.

In fact, we do not have to use this method at all. Instead, we can use ternary operator to check the present state of the color.

As a result, our Flutter App will work as before.


Why we need enum in Flutter_ second example
Why we need enum in Flutter_ second example

However, the total lines of code reduces from 122 to 112.

Let us see the full code.

import 'package:flutter/material.dart';

// this is a new branch enum and color change

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Happiness Calculator'),
    );
  }
}

//TODO: we will use enum in this branch

enum ContainerColor {
  first,
  second,
}

const inactiveColor = Colors.amber;
const activeColor = Colors.red;

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ContainerColor? selectedContainer;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              children: [
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(18.0),
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          selectedContainer = ContainerColor.first;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        color: selectedContainer == ContainerColor.first
                            ? activeColor
                            : inactiveColor,
                        width: 250.0,
                        height: 250.0,
                        child: const Text('Press Me'),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(18.0),
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          selectedContainer = ContainerColor.second;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        color: selectedContainer == ContainerColor.second
                            ? activeColor
                            : inactiveColor,
                        width: 250.0,
                        height: 250.0,
                        child: const Text('Press Me'),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

You may compare this code snippet with the previous code snippet.

Now, the Container color enum data, controls the color of the Container Widget.

Lines of code reduce. At the same time, it becomes easier to read.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

4 responses to “How to use ternary operator in Flutter”

  1. […] have learned how to use enum. After that, we have used ternary operator to reduce the code […]

  2. […] we have discussed enum before. Secondly, we have reduced the code size by using the ternary operator. And finally, we have discussed Slider in […]

  3. […] During building this Flutter App, we have learned a few key concepts, such as enum, and ternary operator. […]

  4. […] we have learned how to use enum. Secondly, we have learned ternary operator. Thirdly, we have grasped how to customize the Slider […]

Leave a Reply