flutter - Flutter 从没有上下文的 UI 中分离逻辑

我是 flutter 的新手,我一直在开发一个应用程序并尝试实现 MVVM 架构以将逻辑与 UI 分离。我将提供程序用作状态管理,并且在通知新数据方面工作正常。但是在使用 AppLocalizations 类和 (snackbar,Toast,Alert Dialog) 显示已翻译的错误消息时,我有两个主要问题,因为验证输入的逻辑在 ViewModel 中,并且这些库需要一个 CONTEXT 才能使用。我发现获取状态管理可以做所有事情,但它有太多问题,比如文档少和责任太多。

请注意,我的应用程序是 90% 的数据输入,因此验证是我逻辑的主要部分,那么对于我的案例来说,最好的解决方案是什么。如果我必须使用 Get Package,我应该注意什么缺点。提前致谢。

回答1

您可以使用 GetBuilder 构建您的 UI 页面和附加到该 UI 页面的控制器。

这是 SplashPage 和 SplashController 的示例

使用 GetBuilder 的 SplashPage 代码

class SplashPage extends StatelessWidget {
      const SplashPage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return GetBuilder<SplashController>(
            init: SplashController(),
            builder: (controller) => Scaffold(
                  body: Container(
                    child: Center(
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            AppImages.logo,
                            width: SizerUtil.width * 0.25,
                            height: SizerUtil.width * 0.25,
                          ),
                          SizedBox(width: 8.sp),
                          Image.asset(
                            AppImages.awaken,
                            width: SizerUtil.width * 0.35,
                            height: SizerUtil.width * 0.35,
                          ),
                        ],
                      ),
                    ),
                  ),
                ));
      }
    }

这是 SplashController 代码

class SplashController extends GetxController {
      @override
      void onInit() {
        super.onInit();
      }
    
      @override
      void onReady() {
        Future.delayed(
            Duration(milliseconds: 1500), () => Get.off(() => OnBoardingPage()));
        super.onReady();
      }
    }

这是教程的链接,GetBuilder 如何工作https://morioh.com/p/cffd79df5304

相似文章

随机推荐

最新文章