서버에서 살아남기

Dart 기본 본문

Dart

Dart 기본

개발롬 2022. 10. 2. 23:07

1. null vs nullable

변수에 null을 할당하고 싶을 땐 '?'를 타입 뒤에 붙여주면 됩니다.
타입 뒤에 ? 가 없다면 null을 할당할 수 없습니다.

void main() {
  String? name = '테스트';
  name = null;
}

null 타입이 들어갈 수 없는 타입이라면 '!' 를 붙여주면 됩니다.

void main() {
  String? name = '테스트';
  print(name!); >> 현재 이 값은 null이 아니다.
}

2. final vs const

두개 다 선언한 변수에 재할당이 불가합니다.

void main() {
  final String? name = '테스트';
  name = '테스트' > 에러

  const String? name2 = '테스트';
  name2 = '테스트' > 에러
}

차이점은 const 의 경우 빌드타임을 알아야 선언 가능 하지만 final은 빌드 타임을 몰라도 선언 가능합니다.

void main() {
  final DateTime now = DateTime.now();  
  const DateTime now = DateTime.now();
}

3. 오퍼레이터

void main() {
  int number = 10;

  // 1 더하기
  number ++;

  // 1 빼기 =
  number --;

  // 더하면서 변수에 저장
  number += 10;

  // 해당 변수가 null이면 해당 값을 할당
  int number = 10;
  number = null;
  number ??= 3;
  print(number); > 3
}

4. 리스트

void main() {
  List<String> textlist = ['text1', 'text2']

  //길이
  print(textlist.length);

  //인덱스 위치
  print(textlist.indexOf('text1');
}

4. Map

Map 함수 뒤에 key, value 의 타입을 선언해줘야합니다.

void main() {
  Map<String, String> dictionary = {
    'Harry' : '해리포터',
    'Ron' : '론',
    'Hermione' : '헤르미온느'
  };

  // 추가
  dictionary.addAll({
    'Voldemort' : '볼드모트'
  });


  // 제거  
  dictionary.remove('Harry');

  // 키 값만 불러오기
  dictionary.keys;

  // 벨류만 불러오기
  dictionary.values;
}

4. Set

List 에서 중복을 제거해줍니다.

void main() {
  Map<String, String> dictionary = {
    'Harry' : '해리포터',
    'Ron' : '론',
    'Hermione' : '헤르미온느'
  };

  // 추가
  dictionary.addAll({
    'Voldemort' : '볼드모트'
  });


  // 제거  
  dictionary.remove('Harry');

  // 키 값만 불러오기
  dictionary.keys;

  // 벨류만 불러오기
  dictionary.values;
}

5. Set

List 에서 중복을 제거해줍니다.

void main() {
  final Set<String> names = {
    'test1',
    'test1',
    'test2',
    'test3'
  };

  // 해당 값이 있는지 bool 로 결과를 보여줌
  names.contains('test1')
}

6. if / switch

void main() {
  // if
  int number = 2;

  if(number.runtimeType == String){
    print(false);
  }else if(number.runtimeType == bool){
    print(false);
  }else {
    print(true);
  }

  // switch
  // switch 의 경우 다음 작업이 실행 안되게 꼭 break 를 꼭 넣어줘야합니다.

  int number2 = 1;

  switch(number2 % 3){
    case 0:
      print('나머지는 0');
      break;

    case 1:
      print('나머지 1');
      break;

    default:
      print('나머지 2');
      break;
  }
}

7. loops

void main() {
  // 선언, 조건, 하나의 루프가 실행될 때 어떤 액션
  for(int i = 0; i < 10; i++){
    print(i);
  }

  // 예시
  List<int> numbers = [1,2,3,4,5,6];

  for(int i=0; i < numbers.length; i++){
    total += numbers[i];
  }  

  // 아래와 같이 루프 안의 요소를 직접 꺼내올 수도 있습니다.
  total = 0;
  for(int number in numbers){
    total += number;
  }

  // while
  int total2 = 0;

  while(total2 < 10){
    total2 +=1;
  }

  // while 문과 break
  int total3 = 0;
  while(total3 < 10){
    total3 +=1;

    if(total3 == 5){
      break;
    }
  }

  // 루프에 continue를 적용시켜 if 절에 일치하면 cotinue
  for(int i=0; i < 10; i++){
    if(i==5){
      continue;
    }
    print(i); >> 1,2,3,4,6,7,8,9
  }
}

8. Enum

값이 정해져 있을 때 해당 값만 강제할 수 있습니다.

enum Status{
  approved,
  pending,
  rejected
}

void main() {
  Status status = Status.pending;

  if(status == Status.approved) {
    print('승인');
  }else if(status == Status.pending) {
    print('대기');
  }else {
    print('거절');
  }
}