Design Patterns in Flutter: a Hands-On Approach With Factory Method

Albert Joao Jimenez
Pragma
Published in
5 min readJul 2, 2024
Pragma — chapter mobile

Based on the Dart language, Flutter stands out for its flexibility and capacity to apply object-oriented programming principles, such as SOLID principles. These fundamentals enable the development of robust and efficient mobile solutions. This article will explore the Factory Method design pattern, a key tool in a Flutter developer’s toolbox. Through my experience, I will show how this pattern can facilitate the creation of objects in applications, ensuring a code structure that is clear and adaptable to changes. While there are several ways to implement design patterns, the goal is to present a practical perspective on using the Factory Method in mobile app development with Flutter, encouraging an approach that benefits individual and collaborative work.

The image shows a representation of a client requesting the creation of an app.
The image shows a representation of a client requesting the creation of an app.

Case Study:

Imagine you’re leading the development of an app for a popular ice cream chain. The business offers a wide variety of ice cream, from those based on water or milk to those with added fruits and sugar. The head office receives data about these ice creams in JSON format, and our challenge is to design a solution that can interpret this diverse data and create corresponding ice cream objects efficiently and accurately. How can we ensure the app can handle this diversity with code that’s easy to maintain and extend? The Factory Method pattern is our answer, providing an elegant way to abstract the complexity of creating objects from structured data.

Step-by-step implementation

After analyzing our client’s requirements, we concluded that the various types of ice cream could be treated as a family of related objects. Although they share many characteristics, their creation process varies, especially when instantiated from JSON data. To free developers from the complexity of this process and ensure consistent object creation throughout the application, we implemented an abstract class IceCreamModel. This class serves as a common interface for all ice creams, defining a standard structure that includes the name and a list of ingredients. In this way, IceCreamModel establishes the contract that all of our ice cream subclasses will follow, ensuring that regardless of their specific type, they are all created following a uniform and consistent protocol.

uml for the implementation of the factory method in our case Study
uml for the implementation of the factory method in our case Study

To keep our Flutter project clean and manageable, we structure the domain layer folders focusing on business logic, using small, cohesive classes. Within ‘domain,’ we have ‘enums’ that house IngredientsEnum, defining the possible ingredients of our ice cream. In ‘interfaces,’ we place IceCreamModel, our abstract class that dictates the common structure of all ice creams. Finally, ‘models’ contain MilkBasedIceCream and WaterBasedIceCream, which concretize the Factory Method pattern, allowing the creation of different ice creams. This organization facilitates the expansion and maintenance of the code, as each piece is well-defined and isolated, which simplifies the addition of new ice cream types in the future and keeps implementing the Factory pattern consistent and centralized.

The directory structure for the domain layer in our Flutter project

The MilkBasedIceCream class, by extending IceCreamModel, conforms to the Factory Method pattern by defining a specific set of ingredients for this type of ice cream. Although this class currently models the data structure necessary for the creation of IceCreamModel objects, the logic for their serialization and deserialization will be delegated to a specialized component. This separation of responsibilities is not only a recommended design practice, but also paves the way for future enhancements. In the following steps, we will see how this class can be extended to handle the conversion between JSON and IceCreamModel objects more efficiently, while maintaining the integrity and consistency of the data model.

adhering to the Factory Method pattern by defining a specific set of ingredients for milk-based ice creams.

Our WaterBasedIceCream class further refines the Factory Method pattern.

utilizing the Factory Method pattern to create instances from JSON data.

Through its fromJson factory constructor, it enables IceCreamModel objects to be created directly from JSON data, giving developers the flexibility to define the name of the ice cream dynamically. In addition, the inclusion of the toJson method prepares the class to interact efficiently with databases, anticipating a scalability that will be fundamental when we approach more advanced patterns such as the Abstract Factory. This advance not only simplifies the process of creating and handling objects, but also aligns the WaterBasedIceCream class with future extensions and improvements in the design of our application.

In a nutshell

The Factory Method pattern is a powerful tool in our development arsenal, allowing us to build applications with robust, scalable, and maintainable components. It establishes a clear framework for object creation, ensuring consistency while preserving the flexibility essential for interactivity and project growth. This pattern shines on its own and complements and integrates seamlessly with other design patterns, laying the foundation for more complex and sophisticated architectures.

To continue your learning journey and discover how you can apply and combine the Factory Method pattern in your Flutter projects, explore the following resources:

https://refactoring.guru/design-patterns/factory-method

[IN SPANISH] Designing with Elegance: Exploring the Factory Pattern in Programming: A video where we delve into implementing the Factory pattern for dummies.

[IN SPANISH] Exploring Creative Patterns in Flutter: Complement to the Factory Pattern (Dart vs. other) :) a video where we analyze vs. with some other programming languages the implementation of the Factory pattern method

--

--

Albert Joao Jimenez
Pragma
Writer for

Desarrollador de soluciones móviles en Flutter/Dart con +20 años de experiencia. Apasionado del arte y la tecnología. Tengo 5 gatos 🐱.