프로그래밍/Dart & Flutter

[기초] Flutter State 관리

bonong 2024. 9. 20. 23:41
반응형

StatelessWidget

기본 구조

class StateLessExample extends StatelessWidget {
  const StateLessExample({super.key});

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

State 상태 값 없이 정적인 페이지에 사용

StatefulWidget
기본 구조

class StatefulExample extends StatefulWidget {
  const StatefulExample({super.key});

  @override
  State<StatefulExample> createState() => _StatefulExampleState();
}

class _StatefulExampleState extends State<StatefulExample> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

상태값에 따라 화면이 변경되는 페이지에 사용

Statefule 위젯에는 state에 대해 init 과 dispose가 존재

class StatefulExample extends StatefulWidget {
  const StatefulExample({super.key});

  @override
  State<StatefulExample> createState() => _StatefulExampleState();
}

class _StatefulExampleState extends State<StatefulExample> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

내부 클래스 안에 선언하여 initState로 State 값을 초기세팅하거나
dispose로 잡고있는 controller 등을 리소스 반납하는 동작을 추가하여 메모리를 최적화 할 수 있다.

추가적으로 위젯에 인자를 받을 수 있다

class StatefulExample extends StatefulWidget {
  final int index;

  const StatefulExample({required this.index, super.key});

  @override
  State<StatefulExample> createState() => _StatefulExampleState();
}

class _StatefulExampleState extends State<StatefulExample> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}

인자는 final로 선언하고 construct에도 넣어준다

Flutter의 Lifecycle

Stateless

Stateless 위젯은 생성, 빌드, 종료로 3단계로 간단하다

 

Stateful

Stateful 위젯은 상태관리를 위한 라이프 사이클이 있다

간단하게만 구성하면

  • creation stateless 위젯과 다르게 여기서는 createState로 state를 관리하는 객체를 생성
  • initState 위젯에 필요한 state를 초기화 하는 단계
  • build 위젯이 나오는 단계 (UI 생성)
  • setState 여기서 값이 변경된다면 재빌드를 한다
  • didUpdateWidget 재빌드 하기위한 메서드
  • deactivate 위젯이 트리에서 제거될때 호출되는 메서드
  • dispose 위젯이 제거 되기전에 리소스반납 등의 과정을 위해 호출

 

반응형