iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Container & Box Model

Container is the Swiss-army box: padding, margins, decoration, constraints, alignment, transforms. Use it sparingly; reach for the more specific widget when one fits.

Container in anger

EXAMPLE
import 'package:flutter/material.dart';

class HeroCard extends StatelessWidget {
    const HeroCard({super.key, required this.title, required this.body});
    final String title, body;

    @override
    Widget build(BuildContext context) {
        return Container(
            margin:  const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            padding: const EdgeInsets.all(20),
            constraints: const BoxConstraints(minHeight: 120),
            decoration: BoxDecoration(
                gradient: const LinearGradient(
                    colors: [Color(0xFF04AA6D), Color(0xFF0294B0)],
                    begin:  Alignment.topLeft,
                    end:    Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                    BoxShadow(
                        color:     Colors.black.withOpacity(0.10),
                        blurRadius: 12,
                        offset:    const Offset(0, 4),
                    ),
                ],
            ),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                    Text(title, style: const TextStyle(color: Colors.white,
                                                       fontSize: 22, fontWeight: FontWeight.w700)),
                    const SizedBox(height: 8),
                    Text(body, style: const TextStyle(color: Colors.white70)),
                ],
            ),
        );
    }
}

// When NOT to reach for Container
//   • Just padding?     →   Padding(padding: …)
//   • Just margin?       →   leave it to the parent's gap / spacing
//   • Just a coloured rect? → ColoredBox / DecoratedBox
//   • Need a card with elevation? → Card
//   • Want to constrain size only? → SizedBox / ConstrainedBox
//   • Want centering only? → Center / Align

Why it matters

Container with only a colour is one widget too many. ColoredBox(color: …, child: …) skips an entire layer of layout work — meaningful at 60fps scrolling.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
Container(
    padding: const EdgeInsets.all(16),
    margin: const EdgeInsets.symmetric(horizontal: 8),
    decoration: BoxDecoration(
        color: Colors.green,
        borderRadius: BorderRadius.circular(8),
    ),
    child: const Text('boxed'),
)
Try it Yourself »

Discussion

Loading…