DEV Community

Cover image for Flutter trick: using LayoutBuilder for responsive designs
Reme Le Hane
Reme Le Hane

Posted on • Originally published at remejuan.substack.com

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),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools