Dart

shin·2022년 5월 30일
0

Dart

목록 보기
1/20
void main (){
  print('Hello');
}

코드가 끝날 때마다 ;를 작성한다.


void main (){
  var name= 'apple';
  
  print(name);
  
  var name2= 'banana';
    
  print(name2);
  
  name = 'red';
  
  print(name);
}

변수를 선언할 때 var를 사용한다
변수의 값을 변경하고 싶을때 var를 작성하지 않고 변수이름만 작성하고 변경할 값을 넣으면 된다.
한번 선언한 변수를 다시 선언 할 수 없다.

변수타입

정수/실수

void main (){
  // 정수
  //integer
  int number1 = 10;
  
  print(number1);
  
  int number2 = -5;
  
  print(number2);
  
}

void main (){
  // 정수
  //integer
  int number1 = 2;
  int number2 = 4;
  
  print(number1 + number2);
  
  print(number1 - number2);
  
  print(number1 / number2);
  
  print(number1 * number2);
  
}

void main (){
  // 실수
  //double
  double number1 = 2.5;
  double number2 = 0.5;
  
  print(number1 + number2);
  
  print(number1 - number2);
  
  print(number1 / number2);
  
  print(number1 * number2);
  
}

Boolean

void main (){
  // 맞다/틀리다
  // Boolean
  bool isTrue = true;
  bool isFalse = false;
  
  print(isTrue);
  print(isFalse);
}

String

void main (){
  // 글자타입
  // String
  String name = 'apple';
  String name2 = 'banana';
  
  print(name);
  print(name2);
  
  print('${name} ${name2}');
  
  print('$name $name2');
  
  print('${name.runtimeType} ${name2}');
  
  print('$name.runtimeType $name2');
}

dynamic

void main (){
  dynamic name = 'apple';
  
  print(name);
  
  dynamic number = 1;
  
  print(number);
  
  var name2 = 'banana';
  
  print(name2);
  
  print(name.runtimeType);
  print(name2.runtimeType);
  
  name = 2;
  //dynamic 타입을 int로 변경시 에러가 발생하지 않는다
  
  name2 = 5;
  //var 타입을 int로 변경시 에러가 발생한다
  
}

var / dynamic 의 차이는 변수값 변경시 var는 타입변경이 되지않고 dynamic은 타입변경이 가능하다

null

void main (){
  // nullable - null이 될 수 있다
  // non-nullable - null이 될 수 없다
  // null - 아무런 값도 있지 않다
  
  String name = 'apple';
  
  print(name);
  
  name = null;
  // null 값을 넣으면 에러가 뜬다. 
  // Stirng 은 null 값을 가질수 없기 때문이다
  
  String? name2 = 'banana';
  
  name2 = null;
  
  print(name2);
  // 만약 null값을 가질려면 타입 뒤에 ?를 붙여서 작성하면 된다.
  
  print(name2!);
  // null 타입이 절대로 될 수 없는 타입은 !를 넣어준다.
  
}

? null 이 들어 갈 수있다
?가 없으면 null을 넣을 수 없다.
!를 넣으면 현재 이 값은 null을 갖을 수 없다.

final / const

void main (){
  final String name = 'apple';
  
  print(name);
  
  name = 'red';
  
   
  const String name2 = 'banana';
  
  print(name2);
  
  name = 'yellow';
  
}

final / const 로 선언하면 값을 변경 할 수 없다.

void main (){
  final  name = 'apple';
  
  print(name);
  
  
  const  name2 = 'banana';
  
  print(name2);
}

final / const 는 코드를 작성할 때, 타입을 생략 할 수 있다.

final과 const 차이를 코드로 살펴보면...

void main (){
  final DateTime now = DateTime.now();
  //DateTime.now(); 이 코드가 실행될 때 시간이 출력된다.
  
  print(now);
  
  const DateTime now2 = DateTime.now();
  
  print(now2);
}
  • 코드를 실행하면 에러가 발생한다. 그 이유는 const는 buildtime 값을 알고있어야 하기 때문이다. buildTime이란 코드를 작성하면 이진수로 변환이 되는데 그 순간을 말한다.
  • buildtime 값을 알고있어야 한다 의미는 코드를 작성하는 순간에 값이 정해져 있어야 된다는 의미이다.
  • const에서 DateTime.now();는 코드가 실행될 때 값이 정해지는 것이기 때문에 에러가 발생하게 된다.
  • final 경우 buildtime 값을 몰라도 된다.

Operater

void main (){
  int number = 2;
  
  print(number % 2);
  // % 나머지 값을 구할 때 사용한다.
  
  number ++;
  print(number);
  // 1씩 더하기
  
  number --;
  print(number);
  // 1씩 빼기
}
void main (){
  //null
  double? number = 4.0;
  
  print(number);
  
  number = 2.0;
  
  print(number);
  
  number = null;
  
  print(number);
  
  number ??= 3.0;
  
  print(number);
}

?? : null 일 경우 ??오른쪽 값을 사용한다

void main (){
  int number1 = 1;
  
  print(number1 is int);
  print(number1 is String);
  
  print(number1 is! int);
  print(number1 is! String);
}

true
false
false
true
void main (){ 
  // && - and 조건 (모두가 true 조건이면 true, 아니면 false)
  // || - or 조건 (모두가 false 조건이면 false, 아니면 true)
  
  
  bool result = 12 > 10 && 1 > 0;
  
  print(result);
  
  bool result2 = 12 > 10 && 0 > 1;
  
  print(result2);
  
  bool result3 = 12 > 10 || 1 > 0;
  
  print(result3);
  
  bool result4  = 12 > 10 || 0 > 1;
  
  print(result4);
}

true
false
true
true

List

void main(){
  //List
  //리스트
  
  List<String> fruit = ['apple', 'banana', 'orange'];
  List<int> numbers = [1,2,3,4,5,6];
  // 타입에 맞는 값만 넣을 수 있다.
  
  print(fruit);
  print(numbers);
  
  //index
  //순서
  // 0 부터 시작
  print(fruit[0]);
  
  //길이
  print(fruit.length);
  
  //값 추가
  fruit.add('grape');
  
  print(fruit);
  
  //제거
  fruit.remove('grape');
  
  print(fruit);
  
  //index 가져오기
  print(fruit.indexOf('banana'));
}

Map

void main(){
  //Map
  //Key / Value
  
  Map<String, String> dictionary = {
    'apple' : 'red',
    'banana' : 'yellow',
    'grape' : 'purple'
  };
  print(dictionary);
  // 왼쪽이 key, 오른쪽이 value를 의미한다.
  
  
  Map<String, bool> isFruit = {
    'apple' : true,
    'computer' : false
  };
  print(isFruit);
  
  
  // 추가하기
  isFruit.addAll({
    'cat' : false
  });
  print(isFruit);
  
  //key에 해당하는 value 가져오기
  
  print(isFruit['apple']);
  
  //다른 방식으로 추가하기
  
  isFruit['phone'] = false;
  print(isFruit);
  
  //value 변경하기
  isFruit['phone'] = true;
  print(isFruit);
  
  //삭제
  isFruit.remove('cat');
  print(isFruit);
  
  //key, value 값 모두 가져오기
  print(isFruit.keys);
  print(isFruit.values);
  
}

{apple: red, banana: yellow, grape: purple}
{apple: true, computer: false}
{apple: true, computer: false, cat: false}
true
{apple: true, computer: false, cat: false, phone: false}
{apple: true, computer: false, cat: false, phone: true}
{apple: true, computer: false, phone: true}
(apple, computer, phone)
(true, false, true)

Set

void main(){
  // Set
  // Map과 비슷하지만 Key:value 형태가 아니다.
  // List 처럼 하나의 값만 가지고있다
  // List 와 Set의 차이점은 Set에는 중복값이 들어 갈 수 없다.
  // 중복을 자동으로 처리해준다.
  
  final Set<String> names = {
    'apple',
    'banana',
    'grape',
  };
  
  print(names);
  
  names.add('orange');
  
  print(names);
  
  print(names.contains('apple'));
  //값이 존재하는 지 찾을 때 사용하는 함수
}


{apple, banana, grape}
{apple, banana, grape, orange}
true

if문

void main(){
  // if 문
  
  int num = 3;
  
  if(num % 2 == 0){
     print('값이 짝수입니다.');
  }else {
    print('값이 홀수입니다.');
  }
}

else if

조건이 추가된 경우 else if를 사용한다.

void main(){
  // if 문
  
  int num = 3;
  
  if(num % 3 == 0){
     print('나머지가 0입니다');
  }else if(num % 3 == 1 ){
    print('나머지가 1입니다');
  }else{
    print('나머지가 2입니다');
  }
}

switch

void main(){
  // switch
  
  int num = 2;
  
  switch(num % 3 ){
    case 0:
      print('나머지가 0입니다');
      break;
      
    case 1:
      print('나머지가 1입니다');
      break;
      
    default:
      print('나머지가 2입니다');
      break;
  }
}
// ()안에 조건을 넣어준다
// ()안에서 나올 수 있는 값들은 case에 넣어주고
// break로 닫아준다.
// if문에서 else역활을 해주는 기본값 default를 작성한다.

loop

void main(){
  // for loop
  for(int i = 0; i < 10; i++){
    print(i);
  }
}

for loop의 기본형태이다. ()안에 변수를 선언하고 조건을 넣어준 다음에 loop이 한번씩 실행될 때마다 어떤 액션을 취할 건지를 넣어준다.

void main(){
  // for loop
  int total = 0;
  
  List<int> nums = [1,2,3,4,5,6];
  
  for( int i = 0; i < nums.length; i++){
    total += nums[i];
  }
  
  print(total);
  
  total = 0;
  
  for(int num in nums ){
    // in 오른쪽에 있는 값이 loop을 돌면서 왼쪽에 있는 변수에 넣어준다
    print(num);
    total += num;
  }  
  
  print(total);
}

while

void main(){
  //while loop
  
  int total = 0;
  
  while(total < 10){
    // 조건 설정이 중요하다.
    total += 1;
  }
  print(total);
}

break

void main(){
  //break
  
  int total = 0;
  
  while(total < 10){
    total += 1;
    
    if(total == 5){
      break;
    }
  }
  print(total);
  
  total = 0;
  
  for(int i = 0; i < 10; i++){
    total += 1;
    if(total ==5){
      break;
    }
  }
  print(total); 
}

반복문에서 빠져나갈때 사용할 수 있다.

continue

void main(){
  for(int i = 0; i < 10; i++){
    if(i == 5){
      continue;
    }
    print(i);
  }
}

//현재 실행하고 있는 loop만 건너뛴다.
//출력을 하게되면 5는 스킵이 되고 012346789가 출력된다

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('거절입니다.');
  }
}

정확히 사용하는 타입이 정해져 있을때 그 타입만 사용할 수 있게 강제 할 수 있다.
만약에 오타가 발생했을시 에러가 발생하기 때문에 enum을 사용하면 편리하다.

함수

void main(){
  addNumbers(10, 20, 30);
  addNumbers(20, 30, 40);
}

// 세개의 숫자 (x, y, z)를 더하고 짝수인지 홀수인지 알려주는 함수
// parameter / arguement - 매개변수
// postional parameter - 순서가 중요한 파라미터 
// optional parameter - 있어도 되고 없어도 되는 파라미터 []로 감싸준다.
addNumbers(int x, [int y = 20, int z = 30]){
  
  int sum = x + y + z;
  
  print('x : $x');
  print('x : $y');
  print('x : $z');
  
  if( sum % 2 == 0 ){
    print('짝수입니다.');
  }else{
    print('홀수입니다.');
  }
}

0개의 댓글