【问题标题】:Flutter GetX bindings?Flutter GetX 绑定?
【发布时间】:2022-01-08 14:53:14
【问题描述】:

我是这个架构的新手,我对 getX 中的绑定有疑问

我有两个控制器 cartController 和 splashController 我需要这个 cartController 在应用程序的整个生命周期中保持其状态 splashController 仅适用于 splashScreen

但是当我在 GetMaterialApp 的初始绑定中将它与其他控制器绑定时,启动控制器才有效

GetMaterialApp(
      home: const SplashScreen(),
      initialBinding: RootBinding(),
      getPages: [
        GetPage(
          name: SplashScreen.routeName,
          page: () => const SplashScreen(),
        ),
        GetPage(
            name: HomeScreen.routeName,
            page: () => const HomeScreen(),
            children: [
              GetPage(
                name: CategoryScreen.routeName,
                page: () => const CategoryScreen(),
              ),
              GetPage(
                name: AboutScreen.routeName,
                page: () => const AboutScreen(),
              ),
              GetPage(
                name: CartScreen.routeName,
                page: () => const CartScreen(),
              ),
            ]),
      ],
    );

根绑定是

class RootBinding implements Bindings {
  @override
  void dependencies() {
    Get.put<SplashController>(SplashController());
    Get.put<HomeController>(HomeController());
    Get.put<CategoryController>(CategoryController());
    Get.put<AboutController>(AboutController());
  }
}

当我将它更改为 Get.lazyPut() 时它也不起作用

我不知道这是否是上述代码工作的最佳实践,但是当我从初始绑定到页面中删除控制器时,它不会像下面那样工作

GetPage(
   name: SplashScreen.routeName,
   page: () => const SplashScreen(),
   binding: SplashBinding()
   ),

源代码链接 https://github.com/shabhi1997/GetXBaseProject/tree/master

【问题讨论】:

    标签: flutter dart flutter-dependencies dart-pub flutter-getx


    【解决方案1】:

    您可以使用 BindingsBuilder 回调。 每当您访问闪屏时,Getx 都会创建一个闪屏控制器实例,当页面从stack中移除时,GetX 会自动移除闪屏控制器实例。

    GetPage(
       name: SplashScreen.routeName,
       page: () => const SplashScreen(),
       binding: BindingsBuilder(() {
              Get.lazyPut<SplashController>(
                () => SplashController(),
              );
            }))
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2022-12-09
      • 2022-12-04
      • 2022-08-06
      • 2022-08-04
      • 2021-07-25
      • 2023-01-12
      • 2022-11-11
      • 2022-01-10
      相关资源
      最近更新 更多