[Flutter] Global State 관리 (getx)

두꺼비·2023년 7월 2일
0

개발을 하다보면 전역변수 등을 사용해야하는 경우가 생깁니다.
이럴 때 보통 flutter 에서는 Provider를 사용하는데, 오늘은 getx라는 아주 쉬운 도구를 소개할까합니다.

getx를 이용하면 아주 간단한 선언 만으로도 쉽게 상태에 접근이 가능합니다.

1. Gext 설치 & import

pubspec.yaml 파일에 가서 dependencies에 다음과 같이 추가해주세요.

dependencies:
	get: ^4.0.17
import 'package:get/get.dart';

다음과 같이 import 해주시면 됩니다.

2. getx.dart 파일 생성

전역상태를 저장하고 관리할 dart파일을 생성해주세요.

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class Getx extends GetxController{
  double count;
  late Size size;

  void counter(){
      count += 1;
  }
}

3. getx 사용하기

final GetxController = Get.put(Getx()); // 선언
GetxController.counter(); // 함수 접근
GetxController.size = MediaQuery.of(context).size; // 변수 초기화
print(GetxController.count); // 변수 접근
profile
두꺼비는 두껍다

0개의 댓글