[Dart] Dart 기본 문법 –

Flutter를 사용하기 전에 알아야 할 필요가 있어서 배우기 시작했습니다.

변수 문

  • 바르: 자유 선언(‘string’, “string”, 3, 3.14, true 등)
  • 동적: 자유 선언(‘string’, “string”, 3, 3.14, true 등)
  • 내부: 정수형
  • 더블: 실수
  • 부울: 부울 유형
  • : 문자열 유형

  • 목록: 목록 유형
  • 놓다: 유형 설정
  • 지도: 딕셔너리 유형
void main() {
  var var_string = "string with var";
  var var_int = 100;

  dynamic dynamic_string = "string with var";
  dynamic dynamic_int = 100;

  String string1 = "string with double quote";
  String string2 = "string with single quote";

  int number1 = 1;
  int number2 = 100;

  double double1 = 1.1;
  double double2 = 3.14;

  bool bool_true = true;
  bool bool_false = false; 

  List<String> string_list = ("ABC", "가나다");
  List<int> integer_list = (1, 2, 3, 4);

  Map<String, bool> bool_dict = {
    "zero": false,
    "one": true
  };
  Map<String, int> int_dict = {
    "zero": 0,
    "one": 1
  };
}

문법

먼저 다트언어를 접하고 느낀 부분은 다음과 같다.

  • 자바와 유사
  • Python 개발자로서 세미콜론(;)을 추가해야 하는 것은 약간 어색합니다.
  • Python의 f-string과 마찬가지로 $variable을 사용하여 변수를 문자열에 할당할 수 있습니다. (사용 방법은 ${list.length})
  • null 에 대한 이상한 구문도 있었습니다.
  • switch 문이 존재하며 if, while, for, do-while은 C와 동일합니다.
  • For (var a in list) { … } 목록 유형 변수를 반복하는 for in 문이 있습니다.

목록

T는 유형을 포함합니다. string, int, bool 등이 될 수 있습니다.

데이터 순서가 있고 중복값을 허용하는 타입입니다.

List<String> strings = ("apple", "cherry", "egg", "grape", "kiwi");
strings(0) = "APPLE";
​
strings.length;
strings.isEmpty;
strings.isNotEmpty;
​
strings.elementAt(3);
strings.first;
strings.last;
​
strings.add("banana");
strings.insert(0, "zero");
​
strings.sort();
strings.sort((a, b) => a.length.compareTo(b.length));
​
strings.join("-");
​
strings.contains("APPLE");
strings.shuffle();

놓다

T는 유형을 포함합니다. string, int, bool 등이 될 수 있습니다.

이 유형에는 데이터 순서가 없으며 중복 값을 허용하지 않습니다.

순서가 없기 때문에 인덱스로 접근이 불가능하다고 합니다. 순서는 없지만 List와 함께 Iterator 클래스를 상속받았기 때문에 first, last, elementAt 정도는 가능한 것 같다.

Set<String> strings = ("apple", "cherry", "egg", "grape", "kiwi");
​
strings.length;
strings.isEmpty;
strings.isNotEmpty;
​
strings.elementAt(3);
strings.first;
strings.last;
​
strings.add("banana");
strings.join("-");
strings.contains("APPLE");

마련하다 에게

키와 값에는 유형이 포함됩니다. string, int, bool 등이 될 수 있습니다.

  • 딕셔너리 타입의 키 값입니다.
Map<String, int> dictionary = {
  "one": 1,
  "two": 2,
  "three": 3
}
​
dictionary.length;
dictionary.isEmpty;
dictionary.isNotEmpty;
​
dictionary("one");
dictionary.addAll({
  "four": 4,
  "five": 5
});
​
dictionary.containsKey("one");
dictionary.containsValue(2);
​
dictionary.keys;
dictionary.values;
​
print(dictionary.entries);
dictionary.forEach((k, v) => {
  print("$k $v")
});