GetX Binding

需求:所有页面都要使用状态管理

在我们使用GetX 状态管理器的时候,往往每次都是用需要手动实例化一个控制器,这样的话基本页面都需要实例化一次,这样就太麻烦了,而Binding 能解决上述问题,可以在项目初始化时把所有需要进行状态管理的控制器进行统一初始化,接下来看代码演示:

在前面的文章中,我们经常使用Get.put(MyController())来进行控制器实例的创建,这样我们就算不使用控制器实例也会被创建,其实GetX 还提供很多创建实例的方法,可根据不同的业务来进行创建,接下来我们简单介绍一下几个最常用的

  • Get.put(): 不使用控制器实例也会被创建
  • Get.lazyPut(): 懒加载方式创建实例,只有在使用时才创建
  • Get.putAsync(): Get.put() 的异步版版本
  • Get.create(): 每次使用都会创建一个新的实例

第一步:声明需要进行的绑定控制器类

import 'package:get/get.dart';
class BindingHomeController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}
import 'package:get/get.dart';
class BindingMyController extends GetxController {
  var count = 0.obs;
  void increment() {
    count++;
  }
}
import 'package:get/get.dart';
class AllControllerBinding implements Bindings {
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.lazyPut<BindingMyController>(() => BindingMyController());
    Get.lazyPut<BindingHomeController>(() => BindingHomeController());
  }
}

第二步:在项目启动时进行初始化绑定

return GetMaterialApp(
  title: "GetX",
  initialBinding: AllControllerBinding(),
  home: GetXBindingExample(),
);

第三步:在页面中使用状态管理器

Obx(() => Text(
  "计数器的值为 ${Get.find<BindingMyController>().count}",
  style: TextStyle(color: Colors.red, fontSize: 30),
)),
SizedBox(height: 20),
ElevatedButton(
  onPressed: () {
    Get.find<BindingMyController>().increment();
  },
  child: Text("点击加1")
),

results matching ""

    No results matching ""