Factory in Flutter

Alvaro Armijos
2 min readDec 24, 2022

--

This pattern is very used in mobile development because many times we must show error or information messages to users. The Factory pattern helps us to have instances of each of those classes given the type. For example we can tell him, Factory give me the error dialog and with that type he already knows which instance he is going to create. If we need to create a new dialog, we do so in the factory and add the new associated type to that instance.

Benefits

  • We know what to request but not the implementation details.
  • We can add or remove as many types as we want and that is controlled by the Factory.

Factory in Flutter

For this pattern we are going to create a simple Factory of messages for the user and depending on the type we request, return the messages.

First we create the message types that we are going to have Error and Success.

Then we create our MessageFactory class, which has a static getDialog method that returns the type of message to display to the user.

Then we create a simple screen, with two buttons to display the Success and Error messages.

The example looks like this:

Finally what you were waiting for, here you can find the complete example:

More Design Patterns in Flutter:

If you like it, you can Buy Me A Coffee!

--

--

Alvaro Armijos

Electronic and Telecommunications Engineer | #Flutter Developer 💙 | Always eager to learn | https://www.linkedin.com/in/alvaro-armijos-sarango/