class CountController extends GetxController{
RxInt count=0.obs;
void increment(){
count.value++;
update();
}
}
GetX是一个简单而强大的依赖管理器,提供了使用 Controller 来管理状态,实现一个自定义 Controller 类继承自 GetxController ,Controller 中进行业务逻辑的处理,当需要改变状态数据时调用 update() 来通知数据改变。
class CountController extends GetxController{
RxInt count=0.obs;
void increment(){
count.value++;
update();
}
}
//创建控制器实例
CountController countController = Get.put(CountController());
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(() => Text("${countController.count}",
style: TextStyle(fontSize: 80))),
ElevatedButton(
onPressed: () {
countController.increment();
},
child: const Text("计数器 + 1")),
ElevatedButton(
onPressed: () {
Get.toNamed("/cart", arguments: {"id": 123});
},
child: const Text("跳转到cart"))
],
),
),
在界面中使用时需要使用 Obx(() => ), 进行包裹,这样使用 Controller 中的数据变化时,调用 update() 后就会刷新界面控件。
//获取计数器实例
Controller controller = Get.find();
第一次使用某个 Controller 时需要进行初始化,后续再使用同一个 Controller 就不需要再进行初始化。 初始化完成后,可以使用 Get.find() 找到对应的 Controller。
每次点击都能改变状态
在不同页面之间切换
在不同页面之间共享状态
将业务逻辑与界面分离
Copyright © 2024 Flutter(flutterschool.cn)