Flutter: sized_context — An easier way to access MediaQuery.size! — gskinner blog

gskinner team
Flutter Community
Published in
2 min readMar 17, 2020

After sharing our simplified screen size detection example to reddit last week, we received a great suggestion from the community: the concept would work even better as a set of extension methods.

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
//You can use:
bool isLandscape = context.isLandscape;
//Get true 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;
//Get % based sizes
double padding = context.widthPct(.02);

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.

For a full list of available methods, check out the example on github where you can also view the source.

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!

--

--