Develop/Dart

Dart 언어 기초_2

dawonny 2022. 1. 31. 23:50
728x90
반응형

https://dartpad.dartlang.org/? 

 

DartPad

 

dartpad.dartlang.org

ref : 코드팩토리 유튜브 채널


enum

  enum Status{
    approved,
    rejected,
    pending,
  }
  
  void main(){
    Status status = Status.approved;
    
    switch(status){
      case Status.approved:
        print('승인상태');
        break;
      case Status.rejected:
        print('거절상태');
        break;
      default:
        print('해당안됨');
        break;
    }
  }

//결과
승인상태

if문

  void main(){
    int number = 2;
    
    if(number %3 ==0){
      print('3의 배수');
      
    }else if(number %4 == 0){
      print('4의 배수');
    }else{
      print('알수없음');
    }
  }

for, for in 

  void main(){
    int total = 0;
    List numlist = [1,2,3,4,5];
    
    for(int i = 0; i < numlist.length; i++){
      total += numlist[i];
    }
    print(total);
  }

while, do while 은 같음.

  void main(){
    int total = 0;
    while(total < 20){
      print(total);
      
      if(total==15){
        break;
      }
      total ++;
    }
  }

함수

  void main(){
    
    double res = linearExp(1,2,3);
    print(res);
  }

double linearExp(double a, double b, double x){
  return a * x + b;
}

함수의 optional parameter

  void main(){
    
    double res = linearExp(1,2,3);
    print(res);
    double res2 = linearExp(1,2);
    print(res2);
    
  }

double linearExp(double a, double x, [double b = 2]){
  return a * x + b;
}

b 는 optional parameter 이다. 디폴트는 2.

나머지 a랑 x는 named parameter 라고 할 수 있겠다.

 


Typedef

  void main(){
   cal(1,2,add);
    cal (1,2,sub);
}

typedef Operation(int x, int y);

void add(int x, int y){
  print('result : ${x+y}');
}

void sub(int x, int y){
  print('result : ${x-y}');
}

void cal(int x, int y, Operation oper){
  oper(x,y);
}

class

  void main(){
   Idol redvelvet = new Idol();
    redvelvet.say();
}

class Idol{
  String name = '레드벨벳';
  
  void say(){
    print('저는 ${this.name}입니다');
  }
}

Constructor Overloading & Named Constructor

  void main(){
   Idol redvelvet = new Idol('레드벨벳');
    redvelvet.say();
}

class Idol{
  final name;
  
  Idol(
    String name,
  ) : this.name = name;
  
  void say(){
    print('저는 ${this.name} 입니다');
  }
}

 

  void main(){
   Idol redvelvet = new Idol('슬기','레드벨벳');
    redvelvet.say();
}

class Idol{
  final name;
  final group;
  
  
  Idol(
    String name,
    String group,
  ) : this.name = name,
  this.group = group;
  
  void say(){
    print('저는 ${this.name} 입니다');
  }
}

 

constructor 오버로딩

void main() {
  Idol seulgi = new Idol('슬기', '레드벨벳');
  seulgi.say();
  
  Idol seulgi2 = new Idol.fromMap({
    'name':'슬기',
    'group':'레드벨벳'
  });
  
  seulgi2.say();
}

class Idol {
  final name;
  final group;

  Idol(
    String name,
    String group,
  )   : this.name = name,
        this.group = group;

  Idol.fromMap(
    Map values,
  )   : this.name = values['name'],
        this.group = values['group'];

  void say() {
    print('저는 ${this.name} 입니다');
  }
}

private 변수는 _(언더바)를 붙여준다.

Dart 에서 private 못가져오는건 파일 단위다.

다른 파일에서 이 클래스에 있는 private 가져오려고 하면 안됨.

void main() {
  Idol seulgi = new Idol('슬기', '레드벨벳',1);
  seulgi.say();

  Idol seulgi2 = new Idol.fromMap({'name': '슬기', 'group': '레드벨벳','id':3,});

  seulgi2.say();
}

class Idol {
  final name;
  final group;
  final _id;

  Idol(
    String name,
    String group,
    int id,
  )   : this.name = name,
        this.group = group,
        this._id = id;

  Idol.fromMap(
    Map values,
  )   : this.name = values['name'],
        this.group = values['group'],
        this._id = values['id'];
  void say() {
    print('저는 ${this.name} 입니다');
  }
}

getter

setter

  get id{
    return this._id;
  }
  
  set id(int id){
    this._id = id;
  }

상속(inheritance)

class BoyGroup extends Idol {
  BoyGroup(
    String name,
    String group,
    int _id,
  ) : super(
          name,
          group,
          _id,
        );

  void sayMale() {
    print('저는 남자 아이돌');
  }
}

class GirlGroup extends Idol {
  GirlGroup(
    String name,
    String group,
    int _id,
  ) : super(
          name,
          group,
          _id,
        );

  void sayFemale() {
    print('저는 여자 아이돌');
  }
}

메소드 오버라이딩

void main() {
  Parent parent = new Parent(3);
  int result = parent.cal();
  print(result);

  Child child = new Child(3);
  int result2 = child.cal();
  print(result2);
}

class Parent {
  final int number;

  Parent(
    int number,
  ) : this.number = number;

  int cal() {
    return this.number * this.number;
  }
}

class Child extends Parent {
  Child(
    int number,
  ) : super(number);

  @override
  int cal() {
    return this.number + this.number;
  }
}

 

void main() {
  Parent parent = new Parent(3);
  int result = parent.cal();
  print(result);

  Child child = new Child(3);
  int result2 = child.cal();
  print(result2);
}

class Parent {
  final int number;

  Parent(
    int number,
  ) : this.number = number;

  int cal() {
    return this.number * this.number;
  }
}

class Child extends Parent {
  Child(
    int number,
  ) : super(number);

  @override
  int cal() {
    int result = super.cal(); //오버라이드해도 부모의 cal이 실행됨
    return result + result;
  }
}

static

인스턴스에 귀속되지 않고 클래스 통째로 귀속이 되는 것.

클래스에 직접 접근하여 사용한다.

(static이 아닌건 인스턴스별로 바꿔줘야하지만 harry.name = 이런식으로

 static인건 클래스에 직접 접근)

void main() {
  Employee harry = new Employee('해리');
  Employee ron = new Employee('론');
  Employee.building = '카카오';
  harry.printNB();
}

class Employee {
  static String building;
  String name;

  Employee(
    String name,
  ) : this.name = name;

  void printNB() {
    print('제이름은 $name 이고 $building에서 근무합니다');
  }

  static void printB() {
    print('$building에서 근무합니다');
  }
}

interface

void main() {
  BoyGroup bts = new BoyGroup('bts');
  bts.say();
}

class IdolInterface{
  void say(){}
}



class BoyGroup implements IdolInterface{
  String name;
  
  BoyGroup(
  String name,
  ) : this.name = name;
  
  void say(){
    print('제 이름은 ${this.name} 입니다.');
  }
}

class GirlGroup implements IdolInterface{
  String name;
  
  GirlGroup(
  String name,
  ) : this.name = name;
  
  void say(){
    print('제 이름은 ${this.name} 입니다.');
  }
}

cascade operator

 

.. 을 사용하면 하나의 객체에 함수 호출, 필드 접근을 순차적으로 수행할 수 있다.

void main() {
  BoyGroup bts = new BoyGroup('bts');
  bts.say();
  bts.saygroup();
  
  new BoyGroup('BTS')
    ..say()
    ..saygroup();
}

class IdolInterface{
  void say(){}
}



class BoyGroup implements IdolInterface{
  String name;
  String group = 'BTS';
  
  BoyGroup(
  String name,
  ) : this.name = name;
  
  void say(){
    print('제 이름은 ${this.name} 입니다.');
  }
  
  void saygroup(){
    print('그룹은 ${this.group} 입니다.');
  }
}

class GirlGroup implements IdolInterface{
  String name;
  
  GirlGroup(
  String name,
  ) : this.name = name;
  
  void say(){
    print('제 이름은 ${this.name} 입니다.');
  }
}

list 심화

void main() {
  List nums = [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
  ];

  print(nums.first);

  print(nums.isEmpty);
  print(nums.isNotEmpty);
  print(nums.length);
  print(nums.last);
  print(nums.reversed);
  nums.add(11);
  nums.addAll([12,13]);
  print(nums);

}

list 탐색

void main() {
  List member = [
    {'id': 0, 'name': '슬기'},
    {'id': 1, 'name': '조이'},
    {'id': 2, 'name': '아이린'},
  ];

  var item = member.firstWhere((item) => item['id'] == 1);

  print(item);

  var index = member.indexWhere((item) => item['id'] == 1);

  print(index);

  var index2 = [10, 20, 30].indexOf(20);

  print(index2);
  
  var contains = [10,20,30].contains(30);
 
  print(contains);
}

forEach

map

fold

reduce 도 알아두자

void main() {
  List member = [
    {'id': 0, 'name': '슬기'},
    {'id': 1, 'name': '조이'},
    {'id': 2, 'name': '아이린'},
  ];

  member.forEach((item) {
    print(item);
  });

  var newList = member.map((item) {
    return item['name']; //name으로만 구성된 list 만들기
  });

  print(newList);

  var fold = member.fold(0, (t, e) {
    // 0부터 시작해서 t에다가 e의 id 를 더함
    return t + e['id'];
  });

  print(fold);
}
void main() {


  List nums=[
    1,2,3,4,5
  ];
  
  nums.remove(3); // 괄호 안의 값(특정값) 삭제
  
  print(nums);
  
  nums.removeAt(0); //0번째 인덱스에 있는 것 삭제
  print(nums);
  
  nums.removeWhere((e) => e == 5); // 값이 5인경우 삭제
  print(nums);
}

 

list를 shuffle 할 수 있는 기능도 있다.


map 심화

 

isEmpty

isNotEmpty

keys

values

length

addAll({ map })

addEntries([ map ]}

 

업데이트하는 함수

void main() {
  Map price = {
    'iphone': 150,
    'Galaxy': 100,
    'Apple Watch': 50,
  };

  price.update('iphone', (prev) {
    // value 값을 업데이트 했다
    return prev * 10;
  });

  print(price);

  price.update('Macbook', (prev) {
    return prev * 10;
  }, ifAbsent: () {
    //Macbook이 없는 경우 2222와 짝지어 추가
    return 2222;
  });
  
  price.putIfAbsent('Macbook Pro', () => 33333333);
  
  print(price);
  
}

 

void main() {
  Map price = {
    'iphone': 150,
    'Galaxy': 100,
    'Apple Watch': 50,
  };

  price.update('iphone', (prev) {
    // value 값을 업데이트 했다
    return prev * 10;
  });

  print(price);

  price.update('Macbook', (prev) {
    return prev * 10;
  }, ifAbsent: () {
    //Macbook이 없는 경우 2222와 짝지어 추가
    return 2222;
  });
  
  price.putIfAbsent('Macbook Pro', () => 33333333);
  
  print(price);
  
  price.updateAll((k,v){
    return v.toString() + '원'; //모든 value에 '원'을 붙이는 걸로 update
  });
  
  price.remove('Apple Watch');
  
  price.removeWhere((k,v){
    return k == 'iphone'; // keyrk iphone 인거 remove
  });
}
728x90
반응형