Skip to main content

Flutter Get Device Screen Width Height with Status Bar

There are inbuilt widget in flutter known as MediaQuery. It is used to find media data in Widget sub tree in flutter. It has a function which can determine device screen width and height. Device width height can be used at many places it's up to us where we want this information. Width always comes in single value but when calculating height of device it is the combination of two values Screen Height + Status bar height.

Flutter Get Device Screen Width Height with Status Bar:

1. Defining a function in our main class getDeviceWidthHeight(). In this function we are calling MediaQuery two functions first for finding width of device other is to find height of device.
  • double width = MediaQuery.of(context).size.width : Get device screen width and store into width variable.
  • double height = MediaQuery.of(context).size.height : Get device screen height with Status bar height included and store into height variable.
  getDeviceWidthHeight(context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    print("Device Width = $width");
    print("Device Height = $height");
  }
2. Creating a button and calling above function on button click.
ElevatedButton(
        style: ElevatedButton.styleFrom(
          fixedSize: const Size(250, 140),
          padding: const EdgeInsets.all(8.0),
          backgroundColor: Colors.green,
          textStyle: const TextStyle(
            fontSize: 21,
          ),
        ),
        onPressed: () => getDeviceWidthHeight(context),
        child: const Text(
          'Get Screen Width Height with Status Bar',
          textAlign: TextAlign.center,
        ),
      ),
3. Complete source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});

  getDeviceWidthHeight(context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    print("Device Width = $width");
    print("Device Height = $height");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: SafeArea(
                child: Center(
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          fixedSize: const Size(250, 140),
          padding: const EdgeInsets.all(8.0),
          backgroundColor: Colors.green,
          textStyle: const TextStyle(
            fontSize: 21,
          ),
        ),
        onPressed: () => getDeviceWidthHeight(context),
        child: const Text(
          'Get Screen Width Height with Status Bar',
          textAlign: TextAlign.center,
        ),
      ),
    ))));
  }
}
Screenshot of app:
Flutter Get Device Screen Width Height with Status Bar
Output Result on Console Windows:

Comments