Building blocks made smaller

Flutter: Reducing widgets boilerplate

Remi Rousselet
2 min readDec 11, 2018

You’ve likely heard of Flutter. And you probably know how powerful widgets are. But they have an issue: they require a good amount of boilerplate.

Let’s analyze our typical widget:

11 lines for a simple Text with arguments is a lot! Due to using classes, we have many duplicates and unnecessary bits of code:

  • Each parameter is declared twice
  • The widget name is written twice too
  • final or super(key: key) are redundant. We never want a widget without these.

Functions would be a perfect fit. It makes the syntax much shorter:

Almost perfect right?

Well, no. Functions have another issue: Functions are not inserted in the Widget tree and therefore are never associated to an Element.

This causes a whole new set of problems, including performance issues or state not properly disposed. See what is the difference between functions and classes? for more information.

… But what if it worked correctly?

Introducing functional_widget, a code generator that generates Widget classes from a function.

Simply write your widget as a function like shown before, decorated by @widget :

And then the code-generator will create a class for you to use, using the name of your function with an uppercase as the first letter:

Notice how BuildContext and Key are not present in the prototype of the function: They are optional. The generated class will still have them, but you don’t have to write things that you don’t use.

I don’t get it, what’s the point?

Basically, this means that instead of classes you can now write functions, but without the issues listed earlier. So you get the benefits of both worlds: Concise and actually works.

Sounds interesting? Go ahead and try it yourself!

--

--

Remi Rousselet

A software engineer passionated in Flutter. You’ll find me most of the time on stackoverflow answering Flutter related questions.