Flutter for Beginners

Dart 기초 문법

Records that rule memory 2025. 2. 18. 10:38
728x90

Dart

Dart 기초 문법 정리

Dart는 객체지향 언어로, Flutter 개발에서 필수적으로 사용됩니다.
Dart의 기초 문법의 기존적인 구조를 살펴본 후 자세한 내용을 다시 알아보도록 하겠습니다.

1. 기본 문법

(1) main() 함수 (프로그램의 시작점)

모든 Dart 프로그램은 main() 함수에서 시작됩니다.

void main() {
  print("Hello, Dart!");
}

print() 함수는 콘솔에 문자열을 출력하는 함수입니다.

(2) 변수와 데이터 타입

Dart는 var, final, const를 포함한 여러 변수 선언 방식을 제공합니다.

void main() {
  int age = 25;            // 정수
  double height = 178.5;   // 실수
  String name = "Dart";    // 문자열
  bool isFlutterFun = true; // 논리형

  var city = "Seoul";  // 타입 추론 가능 (String으로 자동 지정)
  
  final birthYear = 1998; // 변경 불가능한 변수 (런타임 상수)
  const PI = 3.1415; // 컴파일 타임 상수
  
  print("Name: $name, Age: $age, Height: $height, City: $city, Flutter is fun: $isFlutterFun");
}

final vs const

  • final: 실행 중(runtime)에 결정되는 값
  • const: 컴파일 시점(compile-time)에 결정되는 값

(3) 데이터 타입 변환

void main() {
  int number = 10;
  String numToString = number.toString();
  
  String strNum = "20";
  int stringToNum = int.parse(strNum);
  
  print(numToString); // "10"
  print(stringToNum); // 20
}

.toString(), int.parse(), double.parse() 등을 사용하여 변환 가능

2. 연산자

(1) 산술 연산자

void main() {
  int a = 10, b = 3;
  print(a + b);  // 덧셈 (13)
  print(a - b);  // 뺄셈 (7)
  print(a * b);  // 곱셈 (30)
  print(a / b);  // 나눗셈 (3.3333...)
  print(a ~/ b); // 몫 (3)
  print(a % b);  // 나머지 (1)

  String c = "C", d="D";
  // print(a+d); Error: A value of type 'String' can't be assigned to a variable of type 'num'.
  print(c+d);
}

(2) 비교 연산자

void main() {
  int x = 10, y = 20;
  print(x > y);  // false
  print(x < y);  // true
  print(x == y); // false
  print(x != y); // true

  double z = 19.999999999999999; //20과 같은 값으로 인식
  print(y > z);  // false
  print(y < z);  // true
  print(y == z);  // true

  String s = "s";
  //print(y > s);  // Error: A value of type 'String' can't be assigned to a variable of type 'num'.
}

(3) 논리 연산자

void main() {
  bool a = true, b = false;
  print(a && b); // AND (false)
  print(a || b); // OR (true)
  print(!a);     // NOT (false)
}

3. 조건문

(1) if-else 문

void main() {
  int score = 85;
  
  if (score >= 90) {
    print("A 학점");
  } else if (score >= 80) {
    print("B 학점");
  } else {
    print("C 학점");
  }
}

(2) switch-case 문

void main() {
  String grade = "A";
  
  switch (grade) {
    case "A":
      print("우수");
      break;
    case "B":
      print("좋음");
      break;
    default:
      print("보통");
  }
}

switch-case에서는 break 문이 필요합니다.

4. 반복문

(1) for 문

void main() {
  for (int i = 0; i < 5; i++) {
    print("반복: $i");
  }
}

(2) while 문

void main() {
  int i = 0;
  
  while (i < 3) {
    print("while loop: $i");
    i++;
  }
}

(3) do-while 문

void main() {
  int i = 0;
  
  do {
    print("do-while loop: $i");
    i++;
  } while (i < 3);
}
728x90

5. 리스트와 맵 (컬렉션)

(1) 리스트 (배열)

void main() {
  List<String> fruits = ["Apple", "Banana", "Cherry"];
  
  print(fruits[0]); // Apple
  print(fruits.length); // 3
}

Dart에서는 리스트(List)가 배열(Array)와 같은 개념입니다.

(2) 맵 (딕셔너리)

void main() {
  Map<String, int> scores = {
    "Math": 90,
    "English": 85,
    "Science": 95
  };
  
  print(scores["Math"]); // 90
}

Map은 키-값 쌍을 저장하는 컬렉션입니다.

6. 함수

(1) 기본 함수

int add(int a, int b) {
  return a + b;
}

void main() {
  print(add(3, 5)); // 8
}

(2) 화살표 함수 (=>)

int multiply(int a, int b) => a * b;

void main() {
  print(multiply(3, 5)); // 15
}

Dart의 화살표 함수(Arrow Function) 는 단순한 함수 표현식을 간결하게 작성할 수 있도록 도와줍니다.
=> 기호를 사용하여 함수 본문을 한 줄로 줄일 수 있습니다.

 

화살표 함수는 리스트(List), 맵(Map)과 같은 컬렉션 메서드에서 자주 사용됩니다.

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];

  // 각 요소를 제곱한 리스트 반환
  var squaredNumbers = numbers.map((num) => num * num).toList();

  print(squaredNumbers); // [1, 4, 9, 16, 25]
}

(3) 선택적 매개변수

void greet(String name, [String? message]) {
  print("Hello, $name! ${message ?? ''}");
}

void main() {
  greet("Dart"); // Hello, Dart!
  greet("Dart", "Welcome!"); // Hello, Dart! Welcome!
}

7. 클래스와 객체

(1) 클래스 생성

class Person {
  String name;
  int age;
  
  Person(this.name, this.age);
  
  void introduce() {
    print("My name is $name and I am $age years old.");
  }
}

void main() {
  Person p1 = Person("Alice", 30);
  p1.introduce();
}

Dart는 클래스 기반 객체지향 언어입니다.

8. 비동기 프로그래밍 (async/await)

Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  return "Data Loaded!";
}

void main() async {
  print("Loading...");
  String data = await fetchData();
  print(data);
}
728x90