1 代码示例
class CountController extends GetxController { final _count = 0.obs; set count(value) => this._count.value = value; get count => this._count.value; add() => _count.value++; @override void onInit() { super.onInit(); // 值每变一次都会立刻触发 ever(_count, (value) { print("ever -> $value" ); }); // 只有第一次值改变触发 once(_count, (value) { print("once -> $value"); }); // 指定时间后触发回调函数, 在该时间段内值多次改变只会生效一次(最新值) debounce( _count, (value) { print("debounce -> $value"); }, time: Duration(seconds: 2), ); // 指定时间后触发回调函数, 在该时间段内值多次改变只会生效一次(最旧值) interval( _count, (value) { print("interval -> $value"); }, time: Duration(seconds: 1), ); }}
class StateWorkersView extends StatelessWidget { StateWorkersView({Key? key}) : super(key: key); final controller = CountController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GetBuilder"), ), body: Center( child: Column( children: [ // 这里只能用GetX, 用Obx无法调用OnInit GetX<CountController>( init: controller, initState: (_) {}, builder: (_) { return Text('value -> ${_.count}'); }, ), // 按钮 ElevatedButton( onPressed: () { controller.add(); }, child: Text('add'), ), ], ), ), ); }}