본문 바로가기
프로그래밍/Flutter로 앱 서비스 개발하기

[flutter(플러터)]Dart란? (🚩Class) -5

by Mr.noobiest 2022. 5. 31.

함수를 지정하는것처럼 생성자를 1개만들어서  관리하면 동일 플롯을 1개의  class로  정의가 가능하다.

 

 

회원가입을 예시로 들 수 있는데, 이름 / 아이디  / 닉네임 / 이메일처럼 정해진 플롯을 따라 기입하면

1명의 회원을 정의 내릴수 있고   DB로  정리하기도  편리하다.

 

ex)

class Car{
    int seatsCount;
    String Carcolor;
   
   Car(int sts, String col){
       this.seats. = sts;
       this.Carcolor = col;
    }
}
main(){
     Car. newcar1  = new Car(4,'red');
     print('seat : $(newcar1.seats)');
 }

물론 위에처럼 main에서 직접 print 해도 되지만 print도 모듈화할 수 있다.

 

class Car{
    int seatsCount;
    String Carcolor;
   
   Car(int sts, String col){
       this.seats. = sts;
       this.Carcolor = col;
    }

    printCarInfo(){}
        print('seat: $seats, color: $color');
    }

}
main(){
     Car newcar1  = new Car(4,'red');
     newcar1.printCarinfo();
 }

실행결과

seat : 4, color : red

 

 

 

참고로 initial value(초기값)을 설정해줄 수 있는데, 아무것도 입력하지 않을경우 Null이 아닌 기본값을 설정해줄 수 있다.

Car(int sts,  [String col = 'Black']{

     this.seats=sts;

     this.color=col;

}

 

 

그런데 순서대로  기입하지  않으면 에러가 발생하는데 만약 순서가 수십개가  된다면?

이를 방지하기 위해 Map 형으로 하는 방법도 있지만  그냥 중괄호로  지정해준뒤 차후에  순서에 상관없이 설정하는 방법도 있다.

 

Car({int sts,  String col = 'Black'}{
     this.seats=sts;
     this.color=col;
}
Car newCar2 = Car(col:'red',sts:6);
print newCar2.printInfo();

--실행결과--

seats : 6, col : red

 

 

 

만약 생략하면 안되고  반드시 넣어줘야하는 항목이 있다면?@required 어노테이션을 사용하면된다, Dart에는 없는데 flutter에는 있음

Car(int sts,   {@required String col = 'Black'}{
     this.seats=sts;
     this.color=col;
}

 

아니면 그냥  바로 this를 사용해도된다.

Car({this.seats,this.color =. 'black'});

//Car를 생성하는데 "순서에 상관없이" 기본색상은 black인 생성자 클래스

 

728x90
반응형