📘

2022/10/03に公開

# 日本語版:

## 基本

### 例

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("０です")
: 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文の比較

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";

``````

## 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;
``````

ログインするとコメントできます