How to get Device Screen Height and Width in Flutter App

In this example, we are going to show you the easiest way to get device screen width and height in the Flutter app. See the example below for more details.

How to Get Screen Height and Width:

Wrap your Widget with MaterialApp() widget at the root like below:

Widget build(BuildContext context) {
    return MaterialApp( //use MaterialApp() widget like this
      home: Home() //create new widget class for this 'home' to 
                   // escape 'No MediaQuery widget found' error
    );
}

If you don't do this, you may get "No MediaQuery widget found" error. See more details at: ’No MediaQuery widget found’ Error in Flutter.

Now get width and height of device screen like below:

double width = MediaQuery.of(context).size.width;
print(width);
//output: 392.72727272727275

double halfwidth = width * 0.5; //50 % width of screen
print(halfwidth);
//output: 196.36363636363637

double height = MediaQuery.of(context).size.height;
print(height);
//output: 803.6363636363636

double smallheight = height * 0.2; //20 % of height of screen
print(smallheight);
//output: 160.72727272727275

Full Code Example:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    
    double width = MediaQuery.of(context).size.width;
    print(width);
    //output: 392.72727272727275

    double halfwidth = width * 0.5; //50 % width of screen
    print(halfwidth);
    //output: 196.36363636363637

    double height = MediaQuery.of(context).size.height;
    print(height);
    //output: 803.6363636363636

    double smallheight = height * 0.2; //20 % of height of screen
    print(smallheight);
    //output: 160.72727272727275


    return Scaffold(
        appBar: AppBar(
          title: Text("Screen Height and Width"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        body: Container(
            padding: EdgeInsets.all(20),
               child: Container(
                 color: Colors.orange,
                 height: halfwidth,
                 width: smallheight,
               ),
            )
    );
  }
}

Output Screenshot:

In this way, you can get device screen height and width in Flutter App.

No any Comments on this Article


Please Wait...