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. 😉