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,
);
}
}
컨트롤러를 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(
'상점으로 이동하기',
),
),
],
),
),
);
}
}
코인 0으로 만드는 버튼을 눌러야 interval이 실행된다.
처음 어플을 켜자마자 interval이 실행되어야 할 것 같은데..
방법을 생각해보다가
initState를 활용해서 처음에 myCoin을 +1해주는 건 어떨까 생각해봤다.
될지는.. 해봐야겠다...
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;
}
}