Responsive Architecture Flutter

Sahil Hemnani
3 min readJun 4, 2021

This article resolves issues with responsive design for your cross-platform application and make it easy to frame your application’s widgets according to screen size, orientation, device type- you are on the right place!

After facing the same problem(while learning flutter) I tried many different things out such as MediaQuery and some other packages form pub.dev but none was the effective solution for production level application so “Responsive Architecture” was born for me- thanks to filledstacks.com for this awesome architecture.

Building a widget as per screen size:

This widget will take in a Widget for each screen type. If one is not defined it will return the Mobile layout since we’re starting there. This will give us a nice an easily readable top level widget. This widget will take in a Widget for each screen type. If one is not defined it will return the Mobile layout since we’re starting there. This will give us a nice an easily readable top level widget.

class ScreenTypeLayout extends StatelessWidget {
// Mobile will be returned by default
final Widget mobile;
final Widget tablet;
final Widget desktop;

const ScreenTypeLayout(
{Key key, @required this.mobile, this.tablet, this.desktop})
: super(key: key);

@override
Widget build(BuildContext context) {
return ResponsiveBuilder(builder: (context, sizingInformation) {
// If sizing indicates Tablet and we have a tablet widget then return
if (sizingInformation.deviceScreenType == DeviceScreenType.Tablet) {
if (tablet != null) {
return tablet;
}
}

// If sizing indicates desktop and we have a desktop widget then return
if (sizingInformation.deviceScreenType == DeviceScreenType.Desktop) {
if (desktop != null) {
return desktop;
}
}

// Return mobile layout if nothing else is supplied
return mobile;
});
}
}

Building the widget as per the orientation:

The portrait widget is required and will be the default if no landscape widget is supplied. If I were to put this in a package I would make both required and add an assert that says “If you don’t supply both there’s not point in using this widget”.

class OrientationLayout extends StatelessWidget {
final Widget landscape;
final Widget portrait;
OrientationLayout({
Key key,
this.landscape,
@required this.portrait,
}) : super(key: key);

@override
Widget build(BuildContext context) {
var orientation = MediaQuery.of(context).orientation;
if (orientation == Orientation.landscape) {
return landscape ?? portrait;
}

return portrait;
}
}

Examples where this architecture is uses:

A single codebase handles all the cases shown in above two examples.

for any query contact me: LinkedIn or mail at hemnanisahil777@gmail.com

hope it helps, thank you!

--

--