Generic responsive widget
Given a set of breakpoints and knowledge of LayoutBuilder
(or MediaQuery
), we can create a widget with the purpose of deciding what to show based on a set of given breakpoints. The following example outlines the key idea, although there is just one breakpoint.
// ...
class ResponsiveWidget extends StatelessWidget {
final Widget mobile;
final Widget desktop;
const ResponsiveWidget({required this.mobile, required this.desktop});
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < Breakpoints.sm) {
return mobile;
} else {
return desktop;
}
});
}
}
// ...
With a responsive widget, creating responsive content becomes a bit easier. The following example shows the use of the above ResponsiveWidget
for creating a simple screen where the shown widget changes based on the breakpoint.
// ...
class HomeScreen extends StatelessWidget {
Widget build(BuildContext context) {
return ResponsiveWidget(
mobile: Container(color: Colors.green),
desktop: Container(color: Colors.red));
}
}
// ...