GetX series five in Flutter--Works (monitor attribute change callback) usage details

step one:

First customize a class and inherit from GetxController, and then declare the properties of the response.

//必须继承GetxController
class numberVC extends GetxController {
  //声明的变量后面必须跟.obs.当它变化的时候,使用Obx才能够监听到.
  var count = 0.obs;//自定义的属性
  increment() => count++;//自定义的方法

  @override
  void onInit() {
    // TODO: implement onInit
    //当调用Get.put方法的时候,onInit就会执行.
    super.onInit();
    /**使用场景:
     * 当我们在购物车里面增加物品数量的时候,可以在该回调里面计算所有物品的价格
     */
    ever(count, (callback) {
      print("用来监听数字的变化,--$count");
    });

     //只会在变量$第一次改变时才会被调用.
    once(count, (callback) {
      print("只会监听第一次数字的变化,--$count");
    });

    //每次用户停止输入1秒时间调用===>可以用来防止重复提交,
    debounce(count, (callback) {
      print("每次用户停止输入1秒时间调用,--$count");
    },time: Duration(microseconds: 1000));

     //每隔1秒输出一次 .
    interval(count, (callback) {
      print("忽略1秒内所有变化,--$count");
    },time: Duration(microseconds: 1000));


  }
}

Step two:

transfer

 //获取到自定义属性的那个VC(获取到numberVC类的实例)
    final controller = Get.put(numberVC());
//调用属性
Obx(() => Text("${controller.count.toString()}"));

Precautions:

           Works should always be used when starting a Controller or Class. So should always be in oninit (recommended), Class constructor or initState of a StatefulWidget (this is not recommended in most cases and should not have any side effects).

Guess you like

Origin blog.csdn.net/eastWind1101/article/details/128015680