Responsive Architecture Flutter
Building a widget as per the screen:
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 a widget as per 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 used:
- Customizable App Drawer (source code)
- Todo List Application (source code)
Thank you!
A Mobile App Developer Expert | Helping businesses build apps they’re proud to show off—posts about how you can do it too.
3 年Nice, thanks for using the responsive_builder package. It makes things nice and easy ??