The original thought was to add the methods to MediaQuery, which didn’t seem that appealing because it would still be quite verbose to access. Then we realized we could just use the build context directly, which turned out really nice! So nice, that we’ve gone ahead and created a package for it here: https://pub.dev/packages/sized_context.
Now, instead of long MediaQuery.of() calls, or using a utility class, you can simply ask the context it’s size:
import 'package:sized_context/sized_context.dart'; ... Size size = context.sizePx;
It also comes with a few helper methods, like landscape state, inch-based measurement and diagonal screen sizing:
//Instead of: MediaQuery.of(context).orientation == Orientation.landscape bool isLandscape = context.isLandscape; //Get physical device size in inches bool isTablet = context.diagonalInches >= 7; //Access .width and .height directly, no need to go through .size bool useSingleColumn = context.widthPx < 400;
For convenience you can also access the MediaQueryData object directly, to get any other methods or properties:
EdgeInsets padding = context.mq.padding; Size safeSize = context.mq.removePadding();
And just as you would expect, any calls to .size or .mq will automatically bind your view for a rebuild when screen size changes, just as if you were using MediaQuery.of() directly.
Normally we tend to shy away from method extensions unless they are part of fairly well known community package, but this seems like it has the potential to be one of those 🙂
If you feel the library is missing a feature, or you find some issues, please create a ticket. Pull request are also welcome!