I display images loaded from a cloud storage in a full-page mode. I can provide a parameter to an image URL to request a specific size, e.g. match the longest screen dimension. This way I don't have to load 1920px image if the screen is only 1334 pixels.
How can I get the screen size to pass as a parameter?
First, you need to assign a GlobalKey to the widget. If you've assigned the GlobalKey to the widget, you can get the currentContext property of the key and call the findRenderObject() method. The result can be casted to RenderBox . You can get the size from the RenderBox 's size property.
You can use the MediaQuery
class, along with the associated MediaQueryData
to determine your screen size and fetch the correct image. You can then compare the MediaQueryData.size
member with some predefined screen sizes - this will give you the number of logical pixels.
For example, in the build method of a widget:
class MyWidget extends StatelessWidget {
Widget build(BuildContext context) {
// retrieve the mediaQuery data
final mediaQueryData = MediaQuery.of(context);
if (mediaQueryData.size < const Size(100.0, 100.0)) {
// build small image.
} else {
// build big image.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With