Dart 문법

이서혁·2023년 11월 29일
0

Dart

목록 보기
6/6
post-thumbnail

🔶 Variables

변수는 프로그램에서 값을 저장하고 참조할 때 사용하는 중요한 개념이다.

· 변수는 선언과 초기화가 필요하다.
· 변수는 타입이 필요하다.
· Dart는 Null - Safety가 중요하기 때문에 Null을 허용하지 않는 변수를 사용하는 경우 반드시 그 값을 초기화해야 한다.
· 초기화되지 않은 변수는 자동으로 Null 값을 가지게 된다.
· Dart는 변수를 명시적으로 선언해줄 수도 있고, 추론할 수도 있다.

// 변수 선언과 초기화
var name = 'Bob';

// 변수 타입 지정
Object objName = 'Bob';

// 변수 타입 지정 (명시적으로)
String strName = 'Bob';

// final 변수 선언
final finalName = 'Bob';

// const 변수 선언
const bar = 1000000;
const double atm = 1.01325 * bar;
const baz = [];

void main() {
  print(name); // 'Bob' 출력
  print(objName); // 'Bob' 출력
  print(strName); // 'Bob' 출력
  print(finalName); // 'Bob' 출력
  print(baz); // [] 출력
  
}

· late : 초기화를 나중에 하겠다는 표시를 하는 역할을 한다.

class Person {
  late String name;

  void sayHello() {
    print('Hello, my name is $name');
  }
}

void main() {
  var person = Person();
  person.name = 'Alice';
  person.sayHello();
}

final : 한 번 값을 할당하면 변경이 불가능한 키워드 이며, 초기화 후 값을 변경할 수 없다.

import 'dart:math';

void main() {
  // final 변수
  final int finalValue = Random().nextInt(10);
  print("finalValue: $finalValue");
  
  // final 변수 재할당 (오류)
  // finalValue = 10;
  
  // final 변수 변경
  final int finalNewValue = finalValue + 5;
  print("finalNewValue: $finalNewValue");
}

const : 한 번 값을 할당하면 변경이 불가능한 키워드 이며, 값을 변경할 수 없다.

import 'dart:math';

void main() {
// const 변수
  const int constValue = 5;
  print("constValue: $constValue");
  
  // const 변수 재할당 (오류)
  // constValue = 10;
  
  // const 변수 변경 (오류)
  // const int constNewValue = constValue + 5;
}

🔶 Operator

수학적인 연산이나 비교, 논리 등의 기능을 수행하는 기호나 키워드다.

산술 연산자

void main() {
// 산술 연산자
  int a = 10;
  int b = 5;
  print("a + b = ${a + b}"); // 더하기
  print("a - b = ${a - b}"); // 빼기
  print("a * b = ${a * b}"); // 곱하기
  print("a / b = ${a / b}"); // 나누기
  print("a % b = ${a % b}"); // 나머지
}

비교 연산자

void main() {
// 비교 연산자
  print("a > b : ${a > b}");
  print("a < b : ${a < b}");
  print("a >= b : ${a >= b}");
  print("a <= b : ${a <= b}");
  print("a == b : ${a == b}");
  print("a != b : ${a != b}");
}

논리 연산자

void main() {
// 논리 연산자
  bool x = true;
  bool y = false;
  print("x && y : ${x && y}");
  print("x || y : ${x || y}");
  print("!x : ${!x}");
}

할당 연산자

void main() {
// 할당 연산자
  int c = 5;
  c += 3; // c = c + 3;
  print("c : $c");
  c -= 2; // c = c - 2;
  print("c : $c");
  c *= 4; // c = c * 4;
  print("c : $c");
  c ~/= 3; // c = c ~/ 3;
  print("c : $c");
  c %= 2; // c = c % 2;
  print("c : $c");
}

증감 연산자

void main() {
// 증감 연산자
  int d = 7;
  d++; // d = d + 1;
  print("d : $d");
  d--; // d = d - 1;
  print("d : $d");
}

🔶 Keyword

키워드란 Dart 언어에서 특별히 취급하는 단어다.

Dart Type

Numbers

void main() {
  // Numbers
  int a = 10;
  double b = 3.14;
  num c = 1; // num can be either int or double
  print("Numbers:");
  print("a: $a, b: $b, c: $c");
}

Strings

void main() {
// Strings
  String name = "John";
  String greeting = 'Hello, $name!';
  String multiLine = '''
    This is a multi-line string.
    It can cover multiple lines.
    ''';
  print("\nStrings:");
  print("name: $name");
  print("greeting: $greeting");
  print("multiLine: $multiLine");
}

Booleans

void main() {
// Booleans
  bool isTrue = true;
  bool isFalse = false;
  print("\nBooleans:");
  print("isTrue: $isTrue");
  print("isFalse: $isFalse");
}

List

void main() {
// Lists
  List<int> numbers = [1, 2, 3];
  List<String> fruits = ["apple", "banana", "orange"];
  print("\nLists:");
  print("numbers: $numbers");
  print("fruits: $fruits");
}

Maps

void main() {
 // Maps
  Map<String, int> ages = {"John": 30, "Jane": 25};
  Map<String, String> colors = {"apple": "red", "banana": "yellow", "orange": "orange"};
  print("\nMaps:");
  print("ages: $ages");
  print("colors: $colors");
}

Runes

void main() {
// Runes
  Runes input = new Runes('\u{1f600}');
  String smiley = String.fromCharCodes(input);
  print("\nRunes:");
  print("smiley: $smiley");
}

Symbols

void main() {
// Symbols
  Symbol s = #test;
  print("\nSymbols:");
  print(s);
}

Dart Functions

// 메인 함수: 프로그램의 시작점입니다.
void main() {
  // 두 수를 더하는 함수 호출
  int result = add(5, 3);
  print('5 + 3 = $result');
}

// 두 정수를 더하는 함수입니다.
int add(int a, int b) {
  return a + b;
}

Control Flow

if-else

void main() {
  int number = 42;

  // if-else 문을 사용하여 짝수인지 홀수인지 판별합니다.
  if (number % 2 == 0) {
    print('$number 는 짝수입니다.');
  } else {
    print('$number 는 홀수입니다.');
  }
}  

for

void main() {
  int number = 42;
  
// for 반복문을 사용하여 1부터 5까지의 합을 계산합니다.
  int sum = 0;
  for (int i = 1; i <= 5; i++) {
    sum += i;
  }
  print('1부터 5까지의 합: $sum');
}

while

void main() {
  int number = 42;
  
// while 반복문을 사용하여 1부터 10까지의 곱을 계산합니다.
  int product = 1;
  int i = 1;
  while (i <= 10) {
    product *= i;
    i++;
  }
  print('1부터 10까지의 곱: $product');
}

swich

void main() {
  int number = 42;
  
// switch 문을 사용하여 월별 일수를 출력합니다.
  int month = 2;
  int year = 2023;
  int days;

  switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      days = 31;
      break;
    case 4:
    case 6:
    case 9:
    case 11:
      days = 30;
      break;
    case 2:
      if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
        days = 29;
      } else {
        days = 28;
      }
      break;
    default:
      days = 0;
      print('올바른 월이 아닙니다.');
  }

  if (days != 0) {
    print('$year 년 $month 월은 $days 일까지 있습니다.');
  }
}
profile
hommehyuk

0개의 댓글