[Dart] 4장 조건문

 

1. if 문

Dart에서 if문은 특정 조건이 참일 경우에만 실행되는 코드 블록을 정의합니다.

void main() {
  int number = 25;

  if (number > 0) {
    print("양수");
  }
}

2. if-else 문

if-else문은 특정 조건이 참일 경우와 거짓일 경우를 각각 다른 코드 블록에 실행 할 수 있습니다.

void main() {
  int number = -10;

  if (number > 0) {
    print("양수");
  } else {
    print("음수");
  }
}

3. if-else if-else 문

if-else if-else 문은 여러 조건을 순차적으로 검사하여, 첫 번째 참인 조건에 해당하는 블록을 실행합니다.

void main() {
  String Hello = "Hello";

  if (Hello == "Hello") {
    print("${Hello} World");
  } else if (Hello == "Hi") {
    print("My Name");
  } else {
    print("Come on");
  }
}

4.switch 문

switch 문은 여러 값 중 하나와 일치하는 경우에 따라서 다른 코드 블록을 실행할 수 있습니다. 주로 정수, 문자열, 열거형 등에 사용되는 문입니다.

void main() {
  String Sport = "basketball";

  switch (Sport) {
    case "Baseball" || 'baseball':
      print('야구');
      break;
    case "Soccer" || 'soccer':
      print('축구');
      break;
    case "Basketball" || 'basketball':
      print("농구");
      break;
    case 'Rugby' || 'rugby':
      print("럭비");
      break;
    default:
      print("해당 사항 없음");
  }
}

5. 삼항 연산자

삼항 연산자는 간단한 조건문을 한 줄로 표현할 수 있어, 조건식의 결과에 따라 두 개의 값을 선택합니다.

void main() {
  int number = 2;

  String result = (number % 2 == 0) ? "짝" : "홀";

  print(result);
}

6. null 안전성

Dart에는 null 안전성을 제공하여, null 값을 처리할 때 안전하게 코드를 작성할 수 있고, null 체크를 통해 예외 상황을 방지할 수 있습니다.

void main() {
  String? name = 'King';

  if (name != null) {
    print('Hello, $name');
  } else {
    print('Not Use Name');
  }
}

7. 조건문을 활용한 예제

조건문을 조합해 복잡한 논리를 구현할 수 있습니다.

// ignore_for_file: dead_code

void main() {
  num body = 140;
  bool Success = false;

  if (body >= 140) {
    if (Success || body == 180) {
      print("워터 슬라이드 입장 가능");
    } else {
      print('만 12세 이하 입장 불가');
    }
  } else {
    print("140 미만 입장 불가");
  }
}

 

 

GitHub - Koras02/dart-bloging

Contribute to Koras02/dart-bloging development by creating an account on GitHub.

github.com

 

LIST

'Mobile > Dart' 카테고리의 다른 글

[Dart] 6장 함수 정의 및 호출  (0) 2025.03.18
[Dart] 5장 반복문  (0) 2025.03.10
[Dart] 3장 연산자  (0) 2025.03.01
[Dart] 2장 변수 및 데이터 타입  (0) 2025.02.28
[Dart] 1장 Dart란?  (0) 2025.02.26