Ad

Is Is Ok If Show Progress Indicator Inside The Viewmodel Pattern?( Flutter Question)

- 1 answer

I'm using MVVM pattern in my project and i show the spinner inside the viewmodel by passing the build context to the view model method for example :

void getSomeData(BuildContext context,int someDataID){

        showSpinner(context);
}

the mentioned method getSomeData(....) is called from screen file it works fine but i just wanna know will that make any problem?

Thanks

Ad

Answer

I think it is an ok pattern to use but it may cause problems in the future when your app is much bigger. You may either go to debug your viewmodel and view or you want to extend some functionality based on or closely related to the spinner and find it hard to navigate through your code to find what you want as the viewmodel and view are very intertwined.

Strictly speaking the viewmodel should direct the view via state variables held within the viewmodel, rather than allowing the viewmodel to make direct changes to the view via context. This helps keep all the build code in the view and all the logic that controls that in the viewmodel. Below is an example of what I mean using a ChangeNotifier as a viewmodel (using the provider package) e.g.

class ViewModel extends ChangeNotifier {
    bool _showSpinner = false;

    bool get shouldShowSpinner => _showSpinner;

    void showSpinner() {
        _showSpinner = true;
        notifyListeners() // (Method for ChangeNotifiers) Or equivalent call to rebuild the view
    }

    void hideSpinner() {
        _showSpinner = false;
        notifyListeners() // (Method for ChangeNotifiers) Or equivalent call to rebuild the view
    }
}

class View extends StatelessWidget {

    @override
    Widget build(BuildContext context) {
        return ChangeNotifierProvider<ViewModel>(
            create: (context) => ViewModel(),
            child: Consumer<ViewModel>(
                build: (context, model, child) {
                    return Stack(
                        children: [
                            SomePageContents(),
                            if (model.shouldShowSpinner) Spinner(),
                        ],
                    );
                }
            )
        );
    }
}

Just to reiterate, I think this helps maintainability in the long run but if your method works for you, i.e. the scope of your project is relatively small and your original way doesn't cause too many dependency issues then I'd say do it your original way as the MVVM method should help not hinder development.

Ad
source: stackoverflow.com
Ad