Flutter Tip: Use Composition Aggressively

Most widgets in the Flutter SDK use composition aggressively.

By doing the same in our own apps, we can create small, reusable widgets that are easier to reason about.

For example, here's some custom layout code that is used to generate a product page for an eCommerce app:

Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(product.title, style: Theme.of(context).textTheme.titleLarge), gapH8, Text(product.description), // Only show average if there is at least one rating if (product.numRatings >= 1) ...[ gapH8, ProductAverageRating(product: product), ], gapH8, const Divider(), gapH8, Text(priceFormatted, style: Theme.of(context).textTheme.headlineSmall), gapH8, LeaveReviewAction(productId: product.id), const Divider(), gapH8, AddToCartWidget(product: product), ], )

And here's the resulting UI:

For more information about the gapH8 widgets in the code above, read: How to replace SizedBox with compile-time constants for better performance.

Embrace this and banish the massive build method from existence! 💪

Your future self will thank you. 😉

Want More?

Invest in yourself with my high-quality Flutter courses.

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.