Ternary operator in Dart
Tags: flutter, dart
Published: 2021-03-17 11:53:49

---
title: Ternary operator in Dart
published: true
date: 2021-03-15 00:00:00 UTC
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pghq7n8612ewh7p3gzsc.png
tags: 
  - flutter
  - dart
canonical_url: 'https://mukhtharcm.com/dart-ternary-operator/'
---

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.

```dart
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`.

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

Now let’s consider a non-boolean value.

```dart
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`

```dart
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

```dart
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, 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](https://dartpad.dev/0f7f56b1ac8d25939bc53e2397edcac6) 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](https://twitter.com/mukhtharcm). 😊