From Widget to Component

Aymen Toumi
2 min readMay 22, 2019

--

I really hope Flutter team can find a way to utilize a single class to implement the state, instead of creating multiple classes. By moving the state management and user interface building in a state widget we are breaking the Single Responsibility Principle.” @azamsharp

Here, I present my modest approach to overcome this issue. The idea consist of wrapping the desired widget inside a StatefulWidget that preserve the widget state, let the access to defined properties and allow redraw trigger.

Taking in consideration the React development style, I try to imite it’s model so I created this abstract Component class with the necessary items to respect imitable widget attributs and life cycle management.

Without to much speech this is the code file that you should integrated in your project to start defining components. The same code can be used for flutter web.

Now, let’s move to an example that demonstrate how things should be mixed. As usual, I redevelop the famous default counter app using our component model.

The final result will be like this:

In our app we have two mutable widgets the title and the counter each one should be defined as a component.

Let’s start with the title component that every time a new number appears concatenate the previous one to it’s text.

Next, the counter component that should be updated every time the FAB clicked and with some opacity animation:

Finally, the main file:

That’s it!

The github repo is here.

Try it and if you like it give me a clap. Thanks.

--

--