Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of screen in Flutter app?

Tags:

flutter

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?

like image 506
Andrei Volgin Avatar asked Apr 05 '18 04:04

Andrei Volgin


People also ask

How do I get the widget size in flutter?

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.


1 Answers

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.
     }
  }

}
like image 107
Jonah Williams Avatar answered Oct 18 '22 23:10

Jonah Williams