#FreePalestine 🇵🇸

Muhammed Mukhthar CM

Ternary operator in Dart

Mar 15, 2021 2 min read

Ternary Conditional Operators are a pretty useful thing in Dart. They can be used to conditionally show a Flutter widget. They accept 2 operands. If the given condition is true, the first thing will be executed and if it is false, it will execute the second one.

Example in Dart code

void main() {
  bool isComplete = false;
  print(isComplete ? "completed!" : "not Completed");
}
//Outputs not Completed

This will print not completed. If we change the value of isComplete to true, it will print completed.

void main() {
  bool isComplete = true;
  print(isComplete ? "completed!" : "not Completed");
  //Outputs completed 
}

Now let’s consider a non-boolean value.

void main() {
  String name = "John Doe";
  String myName = "mukhtharcm";
  print(name == myName ? "your name is $name " : "your name is NOT $name ");
}
//Outputs your name is NOT John Doe

If we run this code, it’ll print your name is NOT john Doe. But if we change the value of myName to John Doe, it will print your name is John Doe

void main() {
  String name = "John Doe";
  String myName = "John Doe";
  print(name == myName ? "your name is $name " : "your name is NOT $name ");
}
//Outputs your name is John Doe 

Using in Flutter

Ternary Operators are pretty handy when working with Flutter. They can be used to conditionally show widgets. Like showing a CircularProgressIndicator() when loading.

Flutter Example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool isLoading = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            isLoading ? CircularProgressIndicator() : Text("Loading Completed"),
            SizedBox(height: 100),
            Text("Click Floating Action Button Toggle Loading")
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            isLoading = !isLoading;
          });
        },
      ),
    );
  }
}

In the above example, isLoading is a boolean value. Initially it’s value is true. So the CircularProgressIndicator is shown. But the FloatingActionButton toggles the value of isLoading. So the CircularProgressIndicator changes to Text and vice-versa. As we saw above, we can also use values other than boolean here.

If you fancy testing this out in the browser, you can follow this link to see a dartpad filled with sample code for this post.

If you found any typo or have any suggestions, please feel free to contact me on Twitter. 😊

Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.

Join my email list to get the latest posts and updates.


Support Me