How to get Device Screen Size ’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.

See this also: How to Size Widget to Percentage of Screen Height/Width in Flutter

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

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,
               ),
            )
    );
  }
}

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

No any Comments on this Article


Please Wait...