1 代码示例

  1. class CountController extends GetxController {
  2. final _count = 0.obs;
  3. set count(value) => this._count.value = value;
  4. get count => this._count.value;
  5. add() => _count.value++;
  6. @override
  7. void onInit() {
  8. super.onInit();
  9. // 值每变一次都会立刻触发
  10. ever(_count, (value) {
  11. print("ever -> $value" );
  12. });
  13. // 只有第一次值改变触发
  14. once(_count, (value) {
  15. print("once -> $value");
  16. });
  17. // 指定时间后触发回调函数, 在该时间段内值多次改变只会生效一次(最新值)
  18. debounce(
  19. _count,
  20. (value) {
  21. print("debounce -> $value");
  22. },
  23. time: Duration(seconds: 2),
  24. );
  25. // 指定时间后触发回调函数, 在该时间段内值多次改变只会生效一次(最旧值)
  26. interval(
  27. _count,
  28. (value) {
  29. print("interval -> $value");
  30. },
  31. time: Duration(seconds: 1),
  32. );
  33. }
  34. }
  1. class StateWorkersView extends StatelessWidget {
  2. StateWorkersView({Key? key}) : super(key: key);
  3. final controller = CountController();
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: Text("GetBuilder"),
  9. ),
  10. body: Center(
  11. child: Column(
  12. children: [
  13. // 这里只能用GetX, 用Obx无法调用OnInit
  14. GetX<CountController>(
  15. init: controller,
  16. initState: (_) {},
  17. builder: (_) {
  18. return Text('value -> ${_.count}');
  19. },
  20. ),
  21. // 按钮
  22. ElevatedButton(
  23. onPressed: () {
  24. controller.add();
  25. },
  26. child: Text('add'),
  27. ),
  28. ],
  29. ),
  30. ),
  31. );
  32. }
  33. }