MediaQuery
Learning objectives
- You know how to use the MediaQuery widget.
The MediaQuery widget provides access to the properties of the current media. Using the method MediaQuery.of that takes the BuildContext
as a parameter, we receive an instance of MediaQueryData, which contains data about the present device and screen. The following example outlines the same behavior that we looked into when starting to look into the use of LayoutBuilder
.
The above example demonstrates the use of the size property of MediaQueryData
contains the screen size, represented using an instance of a 2D Size class.
Similar to LayoutBuilder
where the function given to builder
is called whenever the screen size changes, widgets with MediaQuery
are rebuilt whenever the values of the corresponding MediaQueryData
change.
The key differences between MediaQuery
and LayoutBuilder
is that MediaQuery
contains generic information about the media (i.e. the device), while LayoutBuilder
contains information about the present widget in the context of the parent widget. In practice, when asking for screen size using MediaQuery
, we always get the actual size of the screen instead of e.g. the constraints of the parent widget. Further, MediaQuery
can be used anywhere with a context (e.g. in a method that is given the context as a parameter), while LayoutBuilder
is a widget.