GET 상태관리 3

김상윤·2025년 9월 4일

flutter

목록 보기
13/13

Get 상태관리 1번 post에 보면 Get.put 메소드가 보인다.
해당 줄을 주석 처리하고 실행하면 어떻게 될까? 그냥 터진다고만 적어놨던듯?

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

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePageController extends GetxController{
  int counter = 0;

  void incrementCounter(){
    counter++;
    update();
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  Widget build(BuildContext context) {
    // Get.put(MyHomePageController());
    return GetBuilder<MyHomePageController>(
      builder: (cont) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text('You have pushed the button this many times:'),
                Text(
                  '${cont.counter}',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: cont.incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    );
  }
}

왜 터질까? 나는 아직 MyHomePageController를 쓰겠다고 선언하고 의존성을 주입하지 않았기 때문이다.
그러다 보니 build() 안에서 MyHomePageController() 안에 있는 변수 counter와 함수 incrementCounter()를 사용하려 하는데 쟤가 뭔데???? 이렇게 나온다고 생각하면 될 듯?

그래서 build() 안에서 Get.Put으로 나 컨트롤러 쓸거고 의존성 주입할게!!! 이렇게 써줘야 하는 것이다.

build() 메소드가 아닌 페이지가 넘어갈 때

Get.to(const NextPage(), binding: BindingsBuilder(() {
  Get.put(DependencyController());
}));

이런식으로 넘기는걸 권장한다지만..ㅠ

그 외의 의존성 주입방법으로 Get.lazyPut()도 있다.

 Get.to(LazyPutPage(), binding: BindingsBuilder(() {
	Get.lazyPut<DependencyController>(() => DependencyController());
  }));

내가 했던 Get.put방식은 page가 넘어가고 UI를 그리기 전에 의존성을 주입하는 반면
Get.lazyPut은 페이지가 변환되고 해당 컨트롤러를 사용할 때 인스턴스가 만들어지는 차이점이 있다!!

그 외에도 Get.putAsync, Get.create 등이 있지만 잘 사용하진 않는듯??

Get.find()

앞서는 컨트롤러를 만들고 인스턴스를 생성한 후에 접근하였다.

그렇다면 이미 만들어진 컨트롤러를 사용하려면 어떻게 해야할까?
답은 Get.find()이다.
만약 앱을 init 하는 시점에 컨트롤러를 Put해놨다면 다른 컨트롤러나 UI 부분에서 이미 인스턴스가 만들어진 컨트롤러에 접근해서 사용할 수 있다.

  initControllers() {
    Get.put(LoginController(auth));
    Get.put(DeviceController());
    Get.put(UserController());
  }

이렇게 한 후 main.dart에서 initController를 호출하면 위 3가지의 컨트롤러가 앱을 실행하면서 먼저 생성이 된다.
그 후에는

final userId = Get.find<UserController>().user?.id;

이런 식으로 해당 컨트롤러에 접근해서 변수나 함수를 사용할 수 있다.

GET은 이 외에도 snackbar 또는 dialog 등 여러가지 편의 기능을 제공한다.

profile
교육 중!

0개의 댓글