[Flutter / Dart] Dart 기초문법(제어문)
1. 제어문
if문, switch문, for문, while문이 있음.
1.1 if문
if문은 원하는 조건을 기준으로 다른 코드를 실행하고 싶을 때 사용함. if문, if else문, else문의 순서대로 괄호 안에 작성한 조건이 true면 해당 조건의 코드 블록이 실행됨.
void main() {
int number = 2;
if (number % 3 == 0) {
print("3의 배수입니다.");
} else if (number % 3 == 1) {
print("나머지가 1입니다.");
} else {
// 조건에 맞지 않는다면 다음 코드 실행
print("맞는 조건이 없습니다.");
}
}
/* 출력값
맞는 조건이 없습니다.
*/
1.2 switch문
입력된 상수값에 따라 알맞은 case블록을 수행함. break 키워드를 사용하면 switch문 밖으로 나갈 수 있음. case끝에 break 키워드를 꼭 사용해야함!(사용하지 않으면 컴파일 에러 발생) enum과 함께 사용하면 유용함
// switch문
enum Status {
approved,
pending,
rejected,
}
void main() {
Status status = Status.approved;
switch (status) {
case Status.approved:
// approved 값이기 때문에 다음 코드가 실행됨.
print("승인 상태입니다.");
break;
case Status.pending:
print("대기 상태입니다.");
break;
case Status.rejected:
print("거절 상태입니다.");
break;
default:
print("알 수 없는 상태입니다.");
}
// Enum의 모든 수를 리스트로 반환함.
print(Status.values);
}
/* 출력값
승인 상태입니다.
[Status.approved, Status.pending, Status.rejected]
*/
1.3 for문
for문은 작업을 여러 번 반복해서 실행할 때 사용함.
void main() {
// 값 선언; 조건 설정; loop마다 실행할 기능
for (int i = 0; i < 3; i++) {
print(i);
}
}
Dart언어에서는 for...in 패턴의 for문도 제공함. 일반적으로 List의 모든 값을 순회하고 싶을 때 사용됨.
void main() {
List<int> numberList = [3, 6, 9];
for (int number in numberList) { // 정수로 이루어진 리스트 [3, 6, 9]가 있고, 그 안에 있는 숫자를 하나씩 꺼내서 출력
print(number);
}
}
/* 출력값
3
6
9
*/
1.4 while문과 do...while문
while문과 do...while문은 for문과 마찬가지로 반복적인 작업을 실행할 때 사용됨. 미리 알아본 for문은 횟수를 기반으로 함수를 반복적으로 실행함. while문은 조건을 기반으로 반복문을 실행함. 조건이 true면 계속 실행, false면 반복을 멈춤.
// while문
void main() {
int total = 0;
while(total < 10) {
total += 1;
}
print(total);
}
/* 출력값
10
*/
위 코드를 보면 `total = 0`으로 초기화 되어있음. `total`이 10보다 작을 때까지 `total`에 1씩 더함.
do...while문은 특수한 형태의 while문임. while문은 조건을 먼저 확인하고 true면 반복문을 실행하지만, do...while은 반복문을 먼저 실행한 후 조건을 확인함.
void main() {
int total = 0;
do {
total +=1;
} while(total < 10);
print(total);
}
/* 출력값
10
*/
위 코드를 보면 `total = 0`으로 초기화 되어있고, 먼저 `total`에 1씩 더함. 언제까지? `total`이 10보다 작을 떄까지.
이러한 차이가 있음.
https://github.com/Leedoseo/Flutter_DartBasic
GitHub - Leedoseo/Flutter_DartBasic
Contribute to Leedoseo/Flutter_DartBasic development by creating an account on GitHub.
github.com
https://www.notion.so/Dart-Flutter-Study-1cf9fd9f157980a5ab7efad394810871?pvs=4
Dart / Flutter Study | Notion
Made with Notion, the all-in-one connected workspace with publishing capabilities.
www.notion.so
출처 : 코드팩토리의 플러터 프로그래밍 3판
'Dart 언어' 카테고리의 다른 글
[Flutter / Dart] Dart 기초문법(함수와 람다) (2) (0) | 2025.04.03 |
---|---|
[Flutter / Dart] Dart 기초문법(함수와 람다) (1) (0) | 2025.04.02 |
[Flutter / Dart] Dart 기초문법(연산자) (0) | 2025.03.31 |
[Flutter / Dart] Dart 기초문법(컬렉션) (0) | 2025.03.29 |
[Flutter / Dart] Dart 기초문법(변수 선언) (0) | 2025.03.17 |