Skip to content

Instantly share code, notes, and snippets.

@dealloc
Created October 26, 2023 14:48
Show Gist options
  • Save dealloc/0673352714cbb271ea00d891545c141e to your computer and use it in GitHub Desktop.
Save dealloc/0673352714cbb271ea00d891545c141e to your computer and use it in GitHub Desktop.
A simple widget that selects the approperiate layout depending on the application width
import 'package:flutter/material.dart';
/// The ResponsiveLayout widget handles showing the corrct widget based on
/// screen sizes.
///
/// Similar to UI libraries like TailwindCSS it chooses the layout on width.
class ResponsiveLayout extends StatelessWidget {
/// The [Widget] shown when the screen size is mobile, this is the default child.
final Widget mobile;
/// The [Widget] shown if the screen size is at least tablet sized.
final Widget? tablet;
/// The [Widget] shown if the screen size is at least desktop sized.
final Widget? desktop;
/// Initializes a [ResponsiveLayout] with [mobile], [tablet] and [desktop].
const ResponsiveLayout(
{super.key, required this.mobile, this.tablet, this.desktop});
@override
Widget build(BuildContext context) {
final desktop = this.desktop;
final tablet = this.tablet;
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 1440 && desktop != null) {
return desktop;
} else if (constraints.maxWidth >= 960 && tablet != null) {
return tablet;
}
return mobile;
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment