Should you prefer composition or inheritance when building Flutter widgets?
TL;DR: Flutter strongly favors composition over inheritance. Build complex widgets by combining smaller ones rather than subclassing. Subclassing StatelessWidget or StatefulWidget is appropriate; subclassing other widgets is not.
Full Answer
The Flutter framework itself is built on composition. Widgets like Padding, Center, and Align are tiny single-purpose units composed into larger structures.
You should extend StatelessWidget or StatefulWidget and compose your UI from existing widgets. You should NOT extend Container, Scaffold, or other concrete widgets.
If you find yourself copying widget code to create variants, extract a shared component widget instead. Use constructor parameters to customize behavior.
Code Examples
A reusable full-width primary button component
Common Mistakes
- โTrying to extend Container or Scaffold โ these widgets don't support inheritance extension points
- โCreating massive 'god widgets' instead of splitting into focused, composable pieces
Interview Tip
Reference Flutter's own documentation: 'Flutter uses composition aggressively.' Show you understand this is a deliberate design philosophy, not a limitation.