📘

Flutterの条件 (三項) 演算子

2022/10/03に公開

日本語版:

基本

条件 (三項) 演算子は、3つのオペランドを取る演算子です。
条件はクエスチョンマーク(?)で、条件が成立した(真値)場合に実行する式とコロン(:)、そして条件が不成立(偽値)の場合に実行する式が最後に来ます。

条件 (三項) 演算子

条件 ? 真値の場合 : 偽値の場合

example.dart
  var myNumber = 22;

  myNumber % 2 == 0 ? print("偶数です") : print("奇数");
example2.dart
  var password = "hiddenpassword";

  password.length >= 6 ? print("パスワード登録出来ました") : print("パスワードが短い");

条件チェーン

三項演算子は右結合で、複数の条件を順番にチェックする「連鎖」が可能です。

example3
  var number = 20;

  number < 0
      ? print("負の数です")
      : number == 0
          ? print("0です")
          : print("正の数です");
example4.dart
  var pts = 40;

  pts < 40
      ? print("不合格")
      : pts < 60
          ? print("再試験")
          : print("合格");

Nullチェック式

この式はダブルクエスチョンマークを使用し、nullのテストに使用します。

Nullチェック式

expr1 ?? expr2

expr1がnon-nullの場合はその値を返し,そうでない場合はexpr2の値を評価し返す。

example5.dart
Center(
        child: Text(name ?? '名前がないです'),
),

三項演算子とIf-else文の比較

三項演算子でできることで、if-elseでできないことがあります。たとえば、定数や参照を初期化する必要がある場合です。

example6.dart
var number = (条件) ? 1 : -1;

English ver:

The Basics

The conditional (ternary) operator is an operator that takes three operands.
The condition is a question mark (?), followed by the expression to be executed if the condition is satisfied by colon (:), and finally the expression to be executed if the condition is not satisfied.

Condition (ternary) operator

Condition ? If true : If false

Example

example.dart
  var myNumber = 22;

  myNumber % 2 == 0 ? print("even number") : print("odd number");
example2.dart
  var password = "hiddenpassword";

  password.length >= 6 ? print("Able to register a password.") : print("password too short");

Condition Chain

Ternary operators can be right-joined to "chain" multiple conditions to be checked in sequence.

example3
  var number = 20;

  number < 0
      ? print("Negative numbers.")
      : number == 0
          ? print("It's 0")
          : print("Positive numbers.");
example4.dart
  var pts = 40;

  pts < 40
      ? print("Failure")
      : pts < 60
          ? print("Re-examination")
          : print("Pass");

Null Check Expression

This expression uses a double question mark and is used to test null case.

Null Check Expression

expr1 ?? expr2

If expr1 is non-null, return its value; otherwise, evaluate and return the value of expr2.

example5.dart
Center(
        child: Text(name ?? 'No name'),
),

Ternary operators and if-else statements

There are some things that can be done with the ternary operator that cannot be done with if-else. For example, you may need to initialize a constant or reference.

example6.dart
var number = (condition) ? 1 : -1;

Discussion