Flutter Provider MVC Implementation

Aymen Toumi
2 min readOct 20, 2020

--

Provider package give us an easy state management system for flutter apps and to make things even easier (as I guess) I try to use Provider as a base to an MVC implementation.

MVC

The Model View Controller (MVC) design pattern specifies that an application consist of a data model, presentation information, and control information. The pattern requires that each of these be separated into different objects.

  • The Model contains only the pure application data, it contains no logic describing how to present the data to a user.
  • The View presents the model’s data to the user. The view knows how to access the model’s data, but it does not know what this data means or what the user can do to manipulate it.
  • The Controller exists between the view and the model. It listens to events triggered by the view (or another external source) and executes the appropriate reaction to these events. In most cases, the reaction is to call a method on the model. Since the view and the model are connected through a notification mechanism, the result of this action is then automatically reflected in the view.

Implementation

  • The Model can be an easy PODO (Plain Old Dart Object).
  • The Controller implementation must give a way to update the model and to refresh the view. Also, it should provide an easy access way to different app controllers.
  • The View must reflect the model presentation and notify controller about different events.

Example

Using the previous class as a base let’s see an example of MVC app. The app consist of 3 bulbs every time a bulb clicked its state will be toggled between (ON/OFF) and if all bulbs are ON the bg color will be light otherwise it’s dark. The app also has a fab once clicked it toggle every bulb state.

Model class

We have only one model class which represents a bulb.

Controller class

For every bulb a controller is set and the bulb controller class must control the model and give informations and update the view.

View class

Every bulb have a view that gives a stateful widget reflecting the model state and interact with controllers.

Also, we have a view for home screen.

Finally, the main class.

Result

Repo

--

--