Flutter trick: using LayoutBuilder for responsive designs

Flutter trick: using LayoutBuilder for responsive designs

When you’re building apps that need to work across different screen sizes (phones, tablets, etc.), LayoutBuilder is a powerful tool to help create adaptive UIs. It lets you access the parent widget’s constraints and make dynamic decisions based on the available space.

Example: Responsive Grid Layout

In this example, we create a grid layout that adjusts the number of columns based on the screen width:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Responsive Grid")),
        body: ResponsiveGrid(),
      ),
    );
  }
}

class ResponsiveGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        // Check the screen width to decide number of columns
        int columns = constraints.maxWidth > 600 ? 4 : 2;

        return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: columns,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
          ),
          itemCount: 20,
          itemBuilder: (context, index) {
            return Container(
              color: Colors.blueAccent,
              child: Center(
                child: Text(
                  "Item $index",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          },
        );
      },
    );
  }
}

How it works:

  • LayoutBuilder: It gives access to the parent constraints (maxWidth in this case), and based on that, we dynamically change the number of columns.
  • Responsive Columns: If the screen width is larger than 600 pixels, we display 4 columns, otherwise, we show 2.

This approach can be extended for other responsive designs as well.