Dart 생성자, 이니셜라이저

이건선·2023년 8월 3일
0

Flutter

목록 보기
25/30

예제 코드 프리뷰

InkWell클래스를 extends해서 InkWellEx.clear를 만들것 입니다. 이 위젯은 물방울 효과가 없는 클릭 이벤트를 실행합니다.

완성 예제

class InkWellEx extends InkWell {
  const InkWellEx.clear({Key? key, onTap, child}) : super(key: key, onTap: onTap, child: child, splashColor: Colors.transparent);
}

InkWellEx.clear에서 'clear'는 명명된 생성자의 이름이며, 다음 괄호 안에 위치한 {Key? key, onTap, child}는 해당 생성자의 파라미터입니다.

super 키워드

  • super 키워드는 부모 클래스의 생성자를 호출하는데 사용됩니다.

  • 이 경우에는 InkWellExInkWell 클래스를 확장하고 있으므로, super는 InkWell의 생성자를 호출합니다.

  • InkWell 생성자는 여러 매개변수를 받는데, 그 중 key, onTap, child, splashColor를 받고 있습니다.

InkWellEx.clear 생성자

  • InkWellEx.clear 생성자는 {Key? key, onTap, child} 이 세 가지 매개변수를 입력받아 super를 호출하고 있습니다.
  • 입력받은 key, onTap, child를 InkWell 생성자에 전달하고, splashColor는 직접적으로 Colors.transparent를 전달하고 있습니다.

완성된 코드는 InkWellEx.clear 위젯을 생성할 때 splashColor는 항상 투명Colors.transparent으로 설정되고, 나머지 세 가지 파라미터는 개발자가 제공하는 값을 사용하게 됩니다.

실행

InkWellEx.clear(
  onTap: () {
    print('Button tapped!');
  },
  child: Text('Tap me'),
),
profile
멋지게 기록하자

0개의 댓글