4. Layout Engine & BoxConstraints

Core Layout Widgets & Sliver Architecture

Master multi-child layouts, Stack positioning, Wrap flow algorithms, and high-performance viewport virtualization using Slivers and CustomScrollView.

1. Multi-Child Layout Mechanics: Row & Column

Row and Column are built on top of the Flex render object. They arrange children linearly along a primary axis:

Row (Horizontal Axis) Column (Vertical Axis) Main Axis (Horizontal: Left <-> Right) Cross Axis (Vertical: Top <-> Bottom) Main Axis (Vertical: Top <-> Bottom) Cross Axis (Horizontal: Left <-> Right)

Alignment Attributes

AttributeOptionsVisual Behavior
mainAxisAlignmentstart, center, end, spaceBetween, spaceAround, spaceEvenlyPositions children along the primary scrolling/flow direction.
crossAxisAlignmentstart, center, end, stretch, baselinePositions children perpendicular to the primary axis (stretch forces children to full cross width/height).
mainAxisSizeMainAxisSize.max (default), MainAxisSize.minmax expands to fill all parent space; min shrink-wraps tightly around its children.

2. Layering UIs: Stack & Positioned

Stack enables overlapping layouts (analogous to CSS position: absolute with z-index determined by child order in the array).

Stack(
  alignment: Alignment.center,
  children: [
    // Bottom Layer: Background Image
    Image.asset('assets/images/card_bg.png', fit: BoxFit.cover),

    // Middle Layer: Semi-transparent Overlay
    Container(color: Colors.black45),

    // Top Layer: Pinned to specific coordinates
    Positioned(
      bottom: 16.0,
      right: 16.0,
      child: FloatingActionButton.small(
        onPressed: () {},
        child: const Icon(Icons.bookmark),
      ),
    ),
  ],
)

3. Virtualized Lists: ListView.builder vs. ListView

When rendering long collections, never instantiate widgets directly inside a default ListView(children: [...]).

Default ListView (Eager Allocation) ListView.builder (Viewport Virtualization) All 10,000 widgets instantiated in RAM simultaneously -> 💥 OutOfMemory! Visible Viewport (Renders only 8 items on screen) Items scrolled off screen are recycled/disposed
// Production-grade Virtualized ListView with itemExtent optimization
ListView.builder(
  itemCount: 10000,
  itemExtent: 72.0, // ⚡ Performance optimization: skips child layout measurement pass!
  itemBuilder: (BuildContext context, int index) {
    return ListTile(
      leading: CircleAvatar(child: Text("$index")),
      title: Text("Transaction #$index"),
    );
  },
)

4. Slivers & CustomScrollView Architecture

Standard scrollable widgets (ListView, GridView) scroll independently. Slivers are portions of a scrollable area that coordinate together under a single unified CustomScrollView and Viewport.

CustomScrollView (Unified Scroll Viewport) 1. SliverAppBar (Collapsing Hero Header) 2. SliverList (Dynamic virtualized rows) 3. SliverGrid (Multi-column gallery) 4. SliverToBoxAdapter (Embeds standard RenderBox)

Complete Sliver Implementation

class AdvancedProfileFeedScreen extends StatelessWidget {
  const AdvancedProfileFeedScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 1. Collapsing Parallax App Bar
          SliverAppBar(
            expandedHeight: 200.0,
            floating: false,
            pinned: true, // Remains visible at top when scrolled
            flexibleSpace: FlexibleSpaceBar(
              title: const Text("Alex Mercer"),
              background: Image.network(
                "https://images.unsplash.com/photo-1579546929518-9e396f3cc809",
                fit: BoxFit.cover,
              ),
            ),
          ),

          // 2. Non-sliver widget adapted into the sliver stream
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                "Activity Overview",
                style: Theme.of(context).textTheme.headlineSmall,
              ),
            ),
          ),

          // 3. Virtualized Sliver Grid
          SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) => Card(child: Center(child: Text("Stat $index"))),
              childCount: 4,
            ),
          ),

          // 4. Virtualized Infinite List
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) => ListTile(title: Text("Feed Item #$index")),
              childCount: 50,
            ),
          ),
        ],
      ),
    );
  }
}

❓ Knowledge Check

Knowledge Check

What is the performance advantage of specifying itemExtent on a ListView.builder?

Knowledge Check

Why can you not place a regular Container directly as a child of a CustomScrollView?

On this page