Flutter: sized_context – An easier way to access MediaQuery.size!

After sharing our simplified screen size detection example to reddit last week, we received a great suggestion from the community: the concept would work 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
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.

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!

shawn.blais

Shawn has worked as programmer and product designer for over 20 years, shipping several games on Steam and Playstation and dozens of apps on mobile. He has extensive programming experience with Dart, C#, ActionScript, SQL, PHP and Javascript and a deep proficiency with motion graphics and UX design. Shawn is currently the Technical Director for gskinner.

@tree_fortress

One Comment

  1. An impressive share! I have just forwarded this onto a coworker
    who has been conducting a little homework on this. And he in fact bought me lunch because I discovered it for him…
    lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for
    spending some time to discuss this issue here on your internet site.

Leave a Reply

Your email address will not be published. Required fields are marked *