0
0
Fluttermobile~5 mins

Responsive layout patterns in Flutter

Choose your learning style9 modes available
Introduction

Responsive layout patterns help your app look good on all screen sizes. They make sure content fits well on phones, tablets, and bigger screens.

You want your app to work on both small phones and large tablets.
You need to adjust the layout when the device orientation changes from portrait to landscape.
You want to show more information on bigger screens and less on smaller ones.
You want buttons and text to resize or rearrange automatically.
You want to avoid content being cut off or too small to read.
Syntax
Flutter
LayoutBuilder(
  builder: (context, constraints) {
    if (constraints.maxWidth < 600) {
      return MobileLayout();
    } else {
      return TabletLayout();
    }
  },
)
Use LayoutBuilder to get the available width and decide layout.
Check constraints.maxWidth to switch between layouts.
Examples
Shows different text depending on screen width.
Flutter
LayoutBuilder(
  builder: (context, constraints) {
    if (constraints.maxWidth < 400) {
      return Text('Small screen');
    } else {
      return Text('Large screen');
    }
  },
)
Uses MediaQuery to get screen width and choose layout.
Flutter
MediaQuery.of(context).size.width < 600 ? MobileView() : DesktopView()
Changes layout direction based on screen width.
Flutter
Flex(
  direction: isWideScreen ? Axis.horizontal : Axis.vertical,
  children: [...],
)
Sample App

This app shows different text depending on the screen width. If the screen is less than 600 pixels wide, it shows "This is a small screen". Otherwise, it shows "This is a large screen".

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

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Responsive Layout Example')),
        body: LayoutBuilder(
          builder: (context, constraints) {
            if (constraints.maxWidth < 600) {
              return const Center(child: Text('This is a small screen'));
            } else {
              return const Center(child: Text('This is a large screen'));
            }
          },
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use LayoutBuilder to get the size of the parent widget and adapt layout accordingly.

MediaQuery gives the full screen size but LayoutBuilder is better for parts of the screen.

Test your app on different devices or use device simulators to see how layouts change.

Summary

Responsive layouts help your app look good on all screen sizes.

Use LayoutBuilder or MediaQuery to get screen size.

Change widgets or layout direction based on screen width.