Rearranging UI elements according to screen size in Flutter
I am using MediaQuery.of(context).size;
in my project in the stable channel to change the layout depending on the width. It works for me without problems. I have written a widget that distinguishes between large screen (tablet) and small screen (smartphone).
class ScreenWidthBuilder extends StatelessWidget { final Widget Function(BuildContext context, bool isAWideScreen) builder; final int bigScreenUpFrom; const ScreenWidthBuilder({Key key, @required this.builder, this.bigScreenUpFrom = 600}) : super(key: key); @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; // screenSize.width changes depending on screen orientation bool isAWideScreen = screenSize.width >= this.bigScreenUpFrom; return this.builder(context, isAWideScreen); }}
First I tried to use the LayoutBuilder
widget but I was able to achieve a better result with MediaQuery.of(context).size;
. With MediaQuery you can request many data about the device screen (size, textScaleFactor, orientation, etc).
For more information have a look at:
- Documentation of LayoutBuilder
- Documentation of MediaQuery and MediaQueryData that gets returned from
MediaQuery.of(context)
.