Flutter Responsive Layout – Mobile, Tablet & Desktop View Helper
Creating a responsive UI in Flutter can be tricky for beginners, especially when building apps that work on mobile, tablet, and desktop. In this guide, we’ll walk you through a simple ResponsiveLayout helper that makes it easy to adapt your widgets to different screen sizes.
π ResponsiveLayout Class
import 'package:flutter/material.dart';
/// Responsive View Helper
class ResponsiveLayout extends StatelessWidget {
final Widget mobile;
final Widget tablet;
final Widget desktop;
const ResponsiveLayout({
Key? key,
required this.mobile,
required this.tablet,
required this.desktop,
}) : super(key: key);
static bool isMobile(BuildContext context) =>
MediaQuery.of(context).size.width < 600;
static bool isTablet(BuildContext context) =>
MediaQuery.of(context).size.width >= 600 &&
MediaQuery.of(context).size.width < 1024;
static bool isDesktop(BuildContext context) =>
MediaQuery.of(context).size.width >= 1024;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 1024) {
return desktop;
} else if (constraints.maxWidth >= 600) {
return tablet;
} else {
return mobile;
}
},
);
}
}
This class takes in three widgets: mobile
, tablet
, and desktop
. Based on the screen width, it decides which widget to render.
π‘ Example: Using ResponsiveLayout in a Home Page
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
static const routeName = "/homepage";
@override
Widget build(BuildContext context) {
return ResponsiveLayout(
mobile: _buildMobileView(),
tablet: _buildTabletView(),
desktop: _buildDesktopView(),
);
}
Widget _buildMobileView() {
return Scaffold(body: Center(child: Text("π± Mobile View")));
}
Widget _buildTabletView() {
return Scaffold(body: Center(child: Text("π» Tablet View")));
}
Widget _buildDesktopView() {
return Scaffold(body: Center(child: Text("π» Desktop View")));
}
}
π Why Use ResponsiveLayout?
- ✅ Easy to implement – no complicated calculations
- π± Works across all screen sizes
- ⚡ Fast development for multi-platform Flutter apps
- π― Cleaner code with separate widgets for each device type
π§ Best Practices for Responsive Flutter Apps
- Use
MediaQuery
to adapt padding, margins, and font sizes - Test on both portrait and landscape modes
- Keep layouts simple and consistent
- Use
Flexible
andExpanded
widgets for adaptive sizing
With this ResponsiveLayout helper, you can quickly make your Flutter app look great on any device – from a small phone screen to a large desktop monitor.