[dart] Don't put any logic in 'createState'. Try moving the logic out of 'createState'

숭글·2023년 8월 15일
0
post-thumbnail

ViewState클래스에 외부에서 받아와야하는 정보가 있어 View에서 ViewState에 parameter로 전달해주려했다.

  • isHost : ViewState에서 필요한 데이터
  • createState()함수 내부에서 생성자를 통해 전달해주려했다.
class View extends StatefulWidget {
  final bool isHost;

  const View({super.key, this.isHost = true});

  
  State<JoinRoomView> createState() => JoinRoomViewState();
}

class ViewState extends State<View> {
  final bool isHost;

  ViewState({required this.isHost});

  
  void initState() {
    super.initState();
    if (isHost) {
      ...
    }
  }

코드를 짜고나니 dart코드에서 warning이 생겼다.

Don't put any logic in 'createState'. Try moving the logic out of 'createState'

참고 페이지

공식 문서에 Bad example로 내가 쓴 것과 똑같은 코드가 나와있는 기분...
정말 별로다 ㄱ-

워닝이라 그냥 둬도 상관은 없지만 수정하고싶은 마음에 구글링을 한 뒤 해결한 방법!

class View extends StatefulWidget {
  final bool isHost;

  const View({super.key, this.isHost = false});

  
  State<JoinRoomView> createState() => JoinRoomViewState(isHost);
}

class ViewState extends State<View> {
  late bool isHost;

  
  void initState() {
 	isHost = widget.isHost;
    super.initState();
    if (isHost) {
      ...
    }
  }

widget : View get widget

자식 클래스에서 widget을 통해 부모 클래스의 프로퍼티에 접근할 수 있다.

훨씬 깔끔한 코드가 됐다 ~_~

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

1개의 댓글

comment-user-thumbnail
2023년 8월 15일

큰 도움이 되었습니다, 감사합니다.

답글 달기