[Flutter] TIL 06

야매·2022년 1월 6일
0

flutter

목록 보기
6/6

List

동일한 타입의 변수들을 모아서 반복해서 뭔가를 할 때 사용한다.
List<Icon> scoreKeeper = [
    Icon(
      Icons.check,
      color: Colors.green,
    ),
    Icon(
      Icons.close,
      color: Colors.red,
    ),
    Icon(
      Icons.close,
      color: Colors.red,
    ),
    Icon(
      Icons.close,
      color: Colors.red,
    ),
    Icon(
      Icons.close,
      color: Colors.red,
    ),
  ];

리스트 이름은 scoreKeeper 이고, Icon인 애들만 리스트안에 들어갈 수 있다.

Row(
          children: scoreKeeper,
        ),

이런식으로 작성된다. Icon이 아닌 애들이 추가되면 error가 뜨기 때문에 주의하자.

void main() {
  List<String> myList = [
    'Angela',
    'James',
    'Katie',
    'Jack',
  ];

리스트는 배열처럼 인덱스로 구성된다. Angela부터 0으로 시작한다.

myList.indexOf('Katie') => 2

myList.add('Ben') => Ben이 추가된다.

리스트에 추가할때는 새 항목이 항상 리스트의 끝에 온다.

myList.insert(2, 'Ben') => 인덱스 2에 Ben이 추가된다.
원하는 위치에 삽입도 가능하다.

https://dart.dev/guides/language/language-tour#lists list에 대한건 참고하기!

생성자

Question 클래스를 생성해서 객체를 만들었다.

>> question.dart
class Question {
  String questionText;
  bool questionAnswer;

  Question({String q, bool a}) {
    questionText = q;
    questionAnswer = a;
  }
}

기존 코드

>> main.dart
List<String> questions = [
    'You can lead a cow down stairs but not up stairs.',
    'Approximately one quarter of human bones are in the feet.',
    'A slug\'s blood is green.',
  ];

List<bool> answers = [false, true, true];

Question q1 = Question(q: 'You can lead a cow down stairs but not up stairs.', a: false);

2개의 리스트를 써야만 했다. 이 2개 리스트를 함께 써주기 위해 앞서 만든 Question 클래스를 이용해 하나의 리스트를 만들어준다. 즉, 질문과 답을 하나의 개체로 만들어준다.

수정 후 코드

List<Question> questionBank = [
  Question(q: 'You can lead a cow down stairs but not up stairs.', a: false),
  Question(q: 'Approximately one quarter of human bones are in the feet.', a: true),
  Question(q: 'A slug\'s blood is green.', a: true),
  ];

이해를 돕기 위한 기본적인 class 코드

void main() {
  Human jenny = Human();
  print(jenny.height);
  jenny.height = 20;
  
  Human james = Human();
  print(james.height);
}

class Human {
  double height = 15;
  int age = 0;
}

jenny와 james는 Human class로부터 생성된 객체이다. 하지만 둘다 height 기본값이 15이다. 어떻게 하면 각각 다른 height를 나타낼 수 있을까?

void main() {
  Human jenny = Human(20);
  print(jenny.height); 	//20
  
  Human james = Human(54);
  print(james.height); 	//54
}

class Human {
  double height = 15;
  int age = 0;
  
  Human(double startingHeight) {
    height = startingHeight;
  }
}

startingHeight를 매개변수로 하여금 height를 직접 지정할 수 있도록 했다.

좀더 코드를 보기 쉽게 하기 위해 약간 수정해보겠다. class 매개변수를 중괄호{ }로 묶어 새로운 Human 객체를 생성해서 사용할 때 이름을 지정한다.

void main() {
  Human jenny = Human(startingHeight: 20);
  print(jenny.height);
  
  Human james = Human(startingHeight: 54);
  print(james.height); 
}

class Human {
  double height = 15;
  int age = 0;
  
  Human({double startingHeight}) {
    height = startingHeight;
  }
}

class 내에 메소드를 생성할수도 있다. 해당 메소드를 접근할때는 동일하게 .으로 표기한다.

void main() {
  Human jenny = Human(startingHeight: 20);
  print(jenny.height);
  
  jenny.talk('Why is the sky blue?');

}

class Human {
  double height = 15;
  int age = 0;
  
  Human({double startingHeight}) {
    height = startingHeight;
  }
  
  void talk(String whatToSay){
    print(whatToSay);
  }
}

캡슐화

파라미터와 메소드를 하나의 클래스에 결합시키는 것을 의미한다. 또한 데이터를 private를 통해서 은닉을 통해 외부에서 접근하지 못하게 막는 것이 중요하다. 사람은 누구나 실수를 할 수 있고 객체이름.파라미터 로 접근하는 방법은 너무나 큰 위험성을 갖고 있다. OOP에서는 내가 갖고있는걸 외부에서 알 필요가 없다면 단순히 숨기는 것이 중요하다.

함수나 property 앞에 _을 붙여서 private로 바꿀 수 있다.

String getQuestionText(int questionNumber) {
    return _questionBank[questionNumber].questionText;
  }

  bool getQuestionAnswer(int questionNumber){
    return _questionBank[questionNumber].questionAnswer;
  }

상속성

상속이란 부모의 특징 및 메소드 들을 그대로 이어 받을 상황일 때 사용한다. 부모의 정보를 물러 받아 다시 구현할 필요없이 재사용성을 늘린 것을 생각하면 된다.
void main() {
  Car myNormalCar = Car();
  print(myNormalCar.numberOfSeat);  //5
  myNormalCar.drive();  //wheels turn
  
  ElectricCar myTesla = ElectricCar();
  myTesla.drive();  //wheels turn
  myTesla.recharge();
}

class Car {
  int numberOfSeat = 5;
  
  void drive() {
    print('wheels turn');
  }
}

class ElectricCar extends Car {
  int batteryLevel = 100;
  
  void recharge(){
    batteryLevel = 100;
  }
}

기존의 Car 클래스의 기능을 확장한다는 의미이다. myTesla.drive()가 저렇게 출력되는 이유는 부모 클래스인 Car 클래스에서 해당 기능을 모두 상속 받았기 때문이다. Car 클래스에서 상속한다는 것은 스스로 반복하고 모든 것을 입력할 필요가 없다는 것을 의미한다.

다형성

void main() {
  LevitatingCar myMagLev = LevitatingCar();
  myMagLev.drive();
}

class LevitatingCar extends Car {
  
  
  void drive() {
    print('glide forwards');
  }
}

LevitatingCar은 Car 클래스의 기능을 상속 받되, 그 중 하나의 기능을 변경하고 싶을때 @기호를 이용하여 재정의 해준다. 그래서 LevitatingCar만의 자체버전의 드라이브를 만들 수 있는 것이다. 부모에게 상속 받았다고 해서 무조건 상속 받은 기능에 대해서만 쓸 수 있는 것은 아니라는거다! 내 입맛대로 기능을 바꿀 수 있음

0개의 댓글