BreakPoints
The BreakPoint can also be used for developing responsive UIs in flutter apps.
const kTabletBreakpoint = 768.0; //breakpoint for a tablet (a tablet's width is 768 px) const kDesktopBreakPoint = 1440.0; //breakpoint for desktop (a desktop screen's width is 1440 px) const kSideMenuWidth = 300.0; // for sidemenu const kNavigationRailWidth = 72.0; // for navigation rail const kMaxWidth = 1180.0; // maximum width
We can use the breakpoints written above to display different UI for different devices. For Example,
Dart
class ResponsiveWidget extends StatelessWidget { const ResponsiveWidget({ Key? key, required this .mobileBody, this .tabletBody, this .desktopBody, }) : super(key: key); final Widget mobileBody; final Widget? tabletBody; final Widget? desktopBody; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, dimens) { // check if the device is a phone if (dimens.maxWidth < kTabletBreakpoint) { return mobileBody; } else if (dimens.maxWidth >= kTabletBreakpoint && dimens.maxWidth < kDesktopBreakPoint) { // returns mobileBody if tabletBody is null return tabletBody ?? mobileBody; } else { // returns mobileBody if desktopBody is null return desktopBody ?? mobileBody; } }, ); } } |
Output:
Shows and hides the AppBar depending on the screen’s width using MedaQuery().
Shows and hides the AppBar depending on the parent’s width using LayoutBuilder().
For more information on handling different UI for different devices, kindly read this article. That’s it. This is all we need in order to get started on building responsive apps with flutter.
Build Responsive UI with Flutter
In this article, we’ll go over the different widgets using which we can build responsive applications with Flutter.