Post

🤯 Just had a massive Eureka moment revisiting Design Patterns. We often treat #Flutter’s BuildContext as some sort of "magic" variable, but while reading about the Strategy Pattern on refactoring.guru today, everything just clicked. Flutter applies this pattern beautifully. 🧵👇

0 reposts1 like

I was reading the definition of "Context" in the Strategy Pattern and found this: "The context isn’t responsible for selecting an appropriate algorithm... the client passes the desired strategy to the context. In fact, the context doesn’t know much about strategies." Sound familiar? 🤔

If we map this directly to Flutter's internal architecture, it fits perfectly: 1️⃣ The Context: It represents the Element (accessed via BuildContext). It persists in the tree. 2️⃣ The Strategy: It represents the Widget. It is the immutable configuration of "how" something should behave or look.

The Element (Context) acts as a generic container, it doesn't know how to paint or layout on its own. In every build() method, we (the Client) pass a NEW "Strategy" (a new Widget) to the Context. "Here Element, this is your new configuration. Run it."

This explains exactly why Widgets must be final and immutable. In the Strategy Pattern, you often don't mutate the active strategy; you simply replace it with a new one to change behavior. Flutter does exactly this: it swaps the Strategy (Widget) to update the UI state.