Tom O'Sullivan
Tom O'Sullivan

Reputation: 4036

How to Determine Screen Height and Width

I've created a new application on Flutter, and I've had problems with the screen sizes when switching between different devices.

I created the application using the Pixel 2XL screen size, and because I've had containers with a child of ListView it's asked me to include a height and width for the container.

So when I switch the device to a new device the container is too long and throws an error.

How can I go about making it so the application is optimized for all screens?

Upvotes: 239

Views: 377537

Answers (15)

Duy Tran
Duy Tran

Reputation: 1167

An update thing is should use .sizeOf instead of .of(context).size to optimize performance

enter image description here

Upvotes: 0

Yash
Yash

Reputation: 6008

You can use:

  • double width = MediaQuery.sizeOf(context).width;
  • double height = MediaQuery.sizeOf(context).height;

To get height just of SafeArea (for iOS 11 and above):

  • var padding = MediaQuery.paddingOf(context);
  • double newheight = height - padding.top - padding.bottom;

Upvotes: 469

CopsOnRoad
CopsOnRoad

Reputation: 268314

Update 3.7.0+

  • Without BuildContext:

    // First get the FlutterView.
    FlutterView view = WidgetsBinding.instance.platformDispatcher.views.first;
    
    // Dimensions in physical pixels (px)
    Size size = view.physicalSize;
    double width = size.width;
    double height = size.height;
    
    // Dimensions in logical pixels (dp)
    Size size = view.physicalSize / view.devicePixelRatio;
    double width = size.width;
    double height = size.height;
    
  • With BuildContext:

    // Dimensions in logical pixels (dp)
    Size size = MediaQuery.of(context).size;
    double width = size.width;
    double height = size.height;
    
    // Height (without SafeArea)
    final padding = MediaQuery.of(context).viewPadding;
    double height1 = height - padding.top - padding.bottom;
    
    // Height (without status bar)
    double height2 = height - padding.top;
    
    // Height (without status and toolbar)
    double height3 = height - padding.top - kToolbarHeight;
    
    // To get above dimensions in physical pixels (px), 
    // multiply them by `MediaQuery.of(context).devicePixelRatio`
    

Upvotes: 144

Adam
Adam

Reputation: 323

Make a Helper file name it

responsive_helper.dart

import 'package:flutter/material.dart';

class ResponsiveHelper {
  static double getDeviceWidth(BuildContext context) {
    return MediaQuery.of(context).size.width * MediaQuery.of(context).devicePixelRatio;
  }

  static double getDeviceHeight(BuildContext context) {
    // Add Additional or Customize To Get Accurate Height
    return MediaQuery.of(context).size.height * MediaQuery.of(context).devicePixelRatio + kToolbarHeight + kBottomNavigationBarHeight;
  }
}

then you can use it like this

double deviceWidth = ResponsiveHelper.getDeviceWidth(context);

if (deviceWidth <= 320) {


} else if (deviceWidth >= 321) {

        
}

and so on

Upvotes: 1

EJ Thayer
EJ Thayer

Reputation: 167

I initially grab the size from MediaQuery in case I need it, then set up a Future to run in 500ms to grab it again. It is correct in the second try. My app is a game that starts with a menu so if size is off a little it does not matter.

Upvotes: -1

Tengo Charlie
Tengo Charlie

Reputation: 31

Initally I also got stucked in to the issue. Then I got to know that for mobile we get the exact screen height using MediaQuery.of(context).size.height but for web we will not use that approach so i have use window.screen.height from dart.html library then I also added the max screen size that we can use in web by making some calculations...


import 'dart:html';
getViewHeight =>
      window.screen!.height! *
      ((window.screen!.height! -
              kToolbarHeight -
              kBottomNavigationBarHeight -
              120) /
          window.screen!.height!);
kIsWeb
? getViewHeight
: MediaQuery.of(context).size.height * 0.7)

By Using this approach we get max usable screen size dynamically.

Upvotes: 3

Giovanni Rasera
Giovanni Rasera

Reputation: 21

 import 'dart:ui';

 var pixelRatio = window.devicePixelRatio;

 //Size in physical pixels
 var physicalScreenSize = window.physicalSize;`

Very good, problem is that when you build for --release it does not work. The reason is that Size is zero at app start so if the code is fast the value of phisicalSize is (0.0, 0.0).

did you find a solution for this ?

Upvotes: 2

ertgrull
ertgrull

Reputation: 1298

To clarify and detail the exact solution for future researchers:

Without context:

import 'dart:ui';

var pixelRatio = window.devicePixelRatio;

 //Size in physical pixels
var physicalScreenSize = window.physicalSize;
var physicalWidth = physicalScreenSize.width;
var physicalHeight = physicalScreenSize.height;

//Size in logical pixels
var logicalScreenSize = window.physicalSize / pixelRatio;
var logicalWidth = logicalScreenSize.width;
var logicalHeight = logicalScreenSize.height;

//Padding in physical pixels
var padding = window.padding;

//Safe area paddings in logical pixels
var paddingLeft = window.padding.left / window.devicePixelRatio;
var paddingRight = window.padding.right / window.devicePixelRatio;
var paddingTop = window.padding.top / window.devicePixelRatio;
var paddingBottom = window.padding.bottom / window.devicePixelRatio;

//Safe area in logical pixels
var safeWidth = logicalWidth - paddingLeft - paddingRight;
var safeHeight = logicalHeight - paddingTop - paddingBottom;

With context:

//In logical pixels
var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;

var padding = MediaQuery.of(context).padding;
var safeHeight = height - padding.top - padding.bottom;

Extra info about physical and logical pixels for the curious: https://blog.specctr.com/pixels-physical-vs-logical-c84710199d62

Upvotes: 81

Tom O&#39;Sullivan
Tom O&#39;Sullivan

Reputation: 4036

A bit late as I had asked the question about 2 years ago and was a newbie back then, but thanks all for the responses as at the time when learning it was a massive help.

To clarify, what I probably should have been asking for was a the Expanded widget, as I believe (hazy memory on what I was trying achieve) I was looking to have a ListView as one of the children of a Column. Instead of using the specific screen size to fit this ListView in the Column I should have been looking to optimise the maximum space available, therefore wrapping the ListView in the Expanded would have had the desired impact.

MediaQuery is great, but I try only to use it to decipher what form factor the screen is using the Material breakpoints, otherwise I try to use the Expanded/Spacer widgets as much as possible, with BoxConstaints on minimum/max sizes, also need to consider the maximum space that is actually available using the SafeArea widget to avoid notches/navigation bar,

Upvotes: 2

Md Jahirul Islam
Md Jahirul Islam

Reputation: 251

Using the following method we can get the device's physical height. Ex. 1080X1920

WidgetsBinding.instance.window.physicalSize.height
WidgetsBinding.instance.window.physicalSize.width

Upvotes: 17

iOS Lifee
iOS Lifee

Reputation: 2201

Just declare a function

Size screenSize() {
return MediaQuery.of(context).size;
}

Use like below

return Container(
      width: screenSize().width,
      height: screenSize().height,
      child: ...
 )

Upvotes: 2

mewadaarvind
mewadaarvind

Reputation: 399

How to access screen size or pixel density or aspect ratio in flutter ?

We can access screen size and other like pixel density, aspect ration etc. with helps of MediaQuery.

syntex : MediaQuery.of(context).size.height

Upvotes: 2

Nikhil Biju
Nikhil Biju

Reputation: 825

Hey you can use this class to get Screen Width and Height in percentage

import 'package:flutter/material.dart';
class Responsive{
  static width(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.width*(p/100);
  }
  static height(double p,BuildContext context)
  {
    return MediaQuery.of(context).size.height*(p/100);
  }
}

and to Use like this

Container(height: Responsive.width(100, context), width: Responsive.width(50, context),);

Upvotes: 4

Hans Zhang
Hans Zhang

Reputation: 509

The below code doesn't return the correct screen size sometimes:

MediaQuery.of(context).size

I tested on SAMSUNG SM-T580, which returns {width: 685.7, height: 1097.1} instead of the real resolution 1920x1080.

Please use:

import 'dart:ui';

window.physicalSize;

Upvotes: 39

Rahul Mahadik
Rahul Mahadik

Reputation: 12291

MediaQuery.of(context).size.width and MediaQuery.of(context).size.height works great, but every time need to write expressions like width/20 to set specific height width.

I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.

Yes, flutter_screenutil plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!

Usage:

Add dependency:

Please check the latest version before installation.

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

Add the following imports to your Dart code:

import 'package:flutter_screenutil/flutter_screenutil.dart';

Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

Use:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

Please refer updated documentation for more details

Note: I tested and using this plugin, which really works great with all devices including iPad

Hope this will helps someone

Upvotes: 9

Related Questions