[TIL] 20241021_ Flutter의 상태관리

ds-k.dev·2024년 10월 21일
0

TIL

목록 보기
4/26

setState()

  • 상태를 변경하고, build함수를 다시 한번 실행시켜 동기화를 시켜주는 함수
 void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  • 이 함수를 실행시키고, build()가 실행되면서 데이터가 동기화된다.

setState()의 한계

  • 앱은 여러 위젯과 동시에 사용된다.
  • setState()는 개별 StatefulWidget 내부에서만 상태를 관리한다.
  • 여러 위젯 사이에서 상태를 전달할 때, 즉 규모가 커졌을때는 복잡성이 증대되어 유지보수하기 힘들어진다.
  • setState는 StatefulWidget 전체를 다시 빌드하는데, 여러 위젯이 겹쳐있는 경우 작은 상태 변화가 전체 위젯 트리를 다시 빌드하게 되어 성능 저하가 일어난다.
  • 전역 상태를 고나리하기 힘들다.

상태관리 라이브러리

  1. Provider
  2. Getx
  3. Bloc/Cubit
  4. Riverpod

GetX 설치

import 'package:get/get.dart'; // 패키지 불러오기

class ProductController extends GetxController {}
  • 만들고자 하는 전역 컨트롤러를 생성
import 'package:get/get.dart'; // getX import
import 'package:setstate_limit_sample/product_controller.dart'; // controller import
import 'package:setstate_limit_sample/stateful_widget_sample.dart';

...

 Widget build(BuildContext context) {
    Get.put(ProductController()); // controller 삽입
    return MaterialApp(
...
  • main.dart에서 get과 컨트롤러 import 후 적용
[GETX] Instance "ProductController" has been created
[GETX] Instance "ProductController" has been initialized
  • Debug console에 이렇게 뜨면 완료

GetX controller와 사용

import 'package:get/get.dart';
class ProductController extends GetxController {
  Set<String> products = {};
  Set<String> leftProducts = {};
  Set<String> rightProducts = {};

  void addProduct(String product) {
    products.add(product);
    update();
  }
}
  • 정의한 컨트롤러 안에 상태와 이벤트 생성

 onPressed: () {
            Get.find<ProductController>()
                .addProduct(StringUtils.getRandomString(2));
          },
  • 상태 변경이 필요한 곳에서 Get.find를 이용해서 이벤트 호출

화면 이동

NavergationBar.push(context, MaterialPageRoute(builder: (context) => ))
  • 일반적인 방법이지만 getX에서 제공하는 Route 기능이 있다.
main.dart에서
MaterialApp -> GetMaterialApp으로 변경

Get.to(XXPage()))
  • 이렇게만 하면 바로 화면을 이동시킬수 있다.

0개의 댓글