Flutter get navigation bar height

Flutter – Get Navigation Bar Height

To retrieve the height of the navigation bar in Flutter, you can use the querying system for physical dimensions provided by the Flutter framework. Specifically, you can utilize the MediaQuery class along with the Padding class to achieve this.

Example:

Suppose you have a Flutter application with a bottom navigation bar, and you want to get the height of that navigation bar. You can do that by following these steps:

  1. In your Flutter project, import the necessary packages:
  2.       import 'package:flutter/material.dart';
        
  3. Create a stateful widget that represents your navigation bar:
  4.       class MyNavigationBar extends StatefulWidget {
            @override
            _MyNavigationBarState createState() => _MyNavigationBarState();
          }
        
  5. Create the state class corresponding to your navigation bar widget:
  6.       class _MyNavigationBarState extends State {
            double navigationBarHeight = 0.0;
            
            @override
            Widget build(BuildContext context) {
              return Scaffold(
                bottomNavigationBar: Padding(
                  padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).padding.bottom,
                    top: MediaQuery.of(context).padding.top,
                  ),
                  child: Container(
                    height: 56.0, // Adjust this according to your navigation bar height
                    color: Colors.blue,
                  ),
                ),
                floatingActionButton: FloatingActionButton(
                  onPressed: () {
                    setState(() {
                      // Get the height of the navigation bar
                      navigationBarHeight = MediaQuery.of(context).padding.bottom + MediaQuery.of(context).padding.top;
                    });
                  },
                  child: Icon(Icons.arrow_circle_up),
                ),
                body: Center(
                  child: Text('Navigation Bar Height: $navigationBarHeight'),
                ),
              );
            }
          }
        
  7. Finally, use this custom navigation bar widget in your main app:
  8.       void main() => runApp(MaterialApp(
            home: Scaffold(
              appBar: AppBar(
                title: Text('Navigation Bar Height Example'),
              ),
              body: MyNavigationBar(),
            ),
          ));
        

With this implementation, you will have a Flutter app with a blue-colored navigation bar. When you tap the floating action button (with an up arrow icon), the height of the navigation bar will be displayed at the center of the screen. The height calculation includes the top and bottom padding values from MediaQuery.

Leave a comment