Flutter完全开发手册
  • Flutter GetView用法、GetxController生命周期

    GetView 是 GetX 库中的一个用于构建视图的组件。它与一个注册的 Controller 关联,并通过 getter 方法提供对该 Controller 的访问。简单的说就是,GetView 简化了 GetX 中对 控制器的访问,GetView<自定义Controller>绑定控制器后可直接使用,避免了写 Get.Find()。

    一、GetView的用法

    第一步:GetView结合GetxController控制器

    
    class UserController extends GetxController{
        RxInt count=0.obs;
    
        void increment(){
          count.value++;
          update();
        }
    }
    

    第二步:GetWiew结合Bindings页面绑定

    
    class UserBinding implements Bindings{
      @override
      void dependencies() {
        // TODO: implement dependencies
    
        Get.lazyPut(() => UserController());
      }
    }
    

    第三步:路由中绑定Binding

    
    GetPage(
    	name: "/user",
    	binding: UserBinding(),
    	page: () => const UserPage(),
    }
    

    第四步:GetView绑定控制器并使用状态管理

    
    Obx(()=>Text("${controller.count}"));
    

    二、GetxController生命周期

    如果是依赖 GetxController,GetX 会自动管理它的生命周期。当这个依赖项被创建时,GetX会调用它的 onInit() 和 onReady()方法;当这个依赖项被删除时,GetX 会调用它的 onClose() 方法。
    
      void onInit() {
        print("onInit");
        super.onInit();
      }
    
      @override
      void onReady() {
        print("onReady");
        super.onReady();
      }
    
      @override
      void onClose() {
        print("onClose");
        super.onClose();
      }
    
    上一篇:Flutter Getx 状态管理、 多页面数据共享 下一篇:Flutter Getx国际化(多语言切换)、GetUtils工具类