[flutter] 과제일지: getX 비트코인

KoEunseo·2023년 10월 13일
0

flutter

목록 보기
24/45

controller

coin_controller.dart

  • onInit 내에서 interval을 사용해 myCoin.value가 +1씩되도록 했다.
  • ever를 사용해 10*n개가 될때마다 알람이 나오도록 했다.
import 'package:get/get.dart';

class CoinController extends GetxController {
  RxInt myCoin = 1.obs;

  CoinController({
    required this.myCoin,
  });

  
  void onInit() {
    super.onInit();
    interval(
      myCoin,
      (callback) => myCoin.value += 1,
    );
    ever(
      myCoin,
      (callback) => (myCoin % 10 == 0) && (myCoin != 0)
          ? Get.snackbar('코인 $myCoin개 돌파', '축하합니다!')
          : null,
    );
  }
}

main_page.dart: get put

컨트롤러를 put하고 Obx 위젯을 사용해 값을 바로 가져올 수 있도록 했다.

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

  
  Widget build(BuildContext context) {
    var controller = Get.put(
      CoinController(
        myCoin: 1.obs,
      ),
    );

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(
              () => Text(
                'Current coin: ${controller.myCoin.value.toString()}',
                style: const TextStyle(
                  fontSize: 30,
                ),
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            FaIcon(
              FontAwesomeIcons.bitcoin,
              color: Colors.yellow.shade700,
              size: 96,
            ),
            TextButton(
              onPressed: () {
                Get.to(
                  const ShopPage(),
                );
              },
              child: const Text(
                '상점으로 이동하기',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

트리거가 있어야 interval이 실행된다.

코인 0으로 만드는 버튼을 눌러야 interval이 실행된다.
처음 어플을 켜자마자 interval이 실행되어야 할 것 같은데..
방법을 생각해보다가
initState를 활용해서 처음에 myCoin을 +1해주는 건 어떨까 생각해봤다.

될지는.. 해봐야겠다...

Future.delayed를 사용해서 트리거를 자동화했다.

import 'package:get/get.dart';

class CoinController extends GetxController {
  RxInt myCoin = 0.obs;

  CoinController({
    required this.myCoin,
  });

  @override
  void onInit() {
    super.onInit();
    //'변경되는동안' 1초마다 호출. 처음 트리거되는 행동이 필요하다.
    interval(
      myCoin,
      (callback) => myCoin.value += 1,
    );

    Future.delayed(const Duration(seconds: 1), () {
      increaseCoin();
    });

    ever(
      myCoin,
      (callback) => (myCoin % 10 == 0) && (myCoin != 0)
          ? Get.snackbar('코인 $myCoin개 돌파', '축하합니다!')
          : null,
    );
  }

  void increaseCoin() {
    myCoin.value += 1;
  }
}

실행화면

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글