Flutter get safe area height

Flutter: Get Safe Area Height

Flutter provides a way to get the safe area height by using the MediaQuery class. The safe area height represents the portion of the screen that is not covered by system bars (like the status bar or navigation bar) and is usually used to avoid rendering content behind these bars.

Example:

Let’s assume we have a Flutter application with a scaffold containing a single widget:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final safeAreaHeight = MediaQuery.of(context).padding.top;

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Safe Area Height Example'),
        ),
        body: Center(
          child: Text(
            'Safe Area Height: $safeAreaHeight',
            style: TextStyle(fontSize: 18),
          ),
        ),
      ),
    );
  }
}
  

In the example above, we access the safe area height by calling MediaQuery.of(context).padding.top. The MediaQuery.of(context) method returns the current media query data, including information about the device’s screen size, orientation, pixel ratio, and more. The padding property of the media query data represents the area that is reserved for system bars on the screen. We retrieve the top padding value to get the safe area height.

The safe area height is then displayed in the body of the Scaffold widget using the Text widget. We use string interpolation to concatenate the safe area height value with the ‘Safe Area Height: ‘ text for better readability.

When you run this example, the app will display the safe area height at the center of the screen. The value will be different depending on the device and its current orientation. If there is no padding set, the safe area height will be 0.

Leave a comment