fluttermvvmflutter-alertdialogflutter-design

Flutter Separating logic from UI Without Context


I'm new to flutter and i've been working on an app and trying to implement the MVVM architecture to separate the logic from the UI. I'm using the provider as state management and it's working fine with notifying the new data. but I have two major problems when it comes to displaying translated error messages using the AppLocalizations class and (snackbar,Toast,Alert Dialog) because the logic for validating the inputs is in the ViewModel and those libraries demands a CONTEXT to work with. i've found the Get State Management that does everything but it has too many issues like less documentation and too many responsibilities.

Note that my application is 90% data entry so validation is a major part of my logic, so what is the best solution for my case. and if I have to use Get Package what is the cons that i should be aware of. Thanks In Advance.


Solution

  • You may use GetBuilder to build you UI page and controller attached to that UI page.

    Here's an example of SplashPage and SplashController

    SplashPage code using GetBuilder

    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,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ));
          }
        }
    

    Here's SplashController Code

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

    Here's the link to tutorial, how GetBuilder works https://morioh.com/p/cffd79df5304