DEV Community

Cover image for Ternary operator in Dart
mukhtharcm
mukhtharcm

Posted on • Originally published at mukhtharcm.com on

Ternary operator in Dart

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
Enter fullscreen mode Exit fullscreen mode

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 
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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;
          });
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, isLoading is a boolean value. Initially, its 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 typos or have any suggestions, please feel free to contact me on Twitter. 😊

Discussion (1)

Collapse
mmanflori profile image
flutterCode

good work .thx