获取Flutter中Scaffold底部导航栏的高度

30

我如何在Flutter中获取ScaffoldBottomNavigationBar的高度?我知道使用MediaQuery.of(context).size可以获取屏幕大小。是否有类似于BottomNavigationBar的方法?

5个回答

22
Container(
   width: MediaQuery.of(context).size.width,
   height: kBottomNavigationBarHeight,
   child: Scaffold(
       backgroundColor: Colors.transparent,
       body: null,
       bottomNavigationBar: BottomNavigationBar()
  )
)

这将创建一个只有足够空间容纳BottomNavigationBar小部件的脚手架。

kBottomNavigationBarHeight是一个常量,可以在constants.dart文件中找到。


8
kBottomNavigationBarHeight是一个常量,但它未考虑到在没有Home键的iPhone或使用最新导航栏的Android设备上可能存在SafeArea填充的情况。 - Christopher Boyd

12

您可以使用key字段来获取小部件的大小。

final key = GlobalKey();
... set key field of widget
double height = key.currentContext.size.height;

7

如果您想知道在带有底部导航栏的主脚手架中的子屏幕中bottomNavigationBar的高度,您可以使用MediaQuery:

final bottomPadding = MediaQuery.of(context).padding.bottom;

底部填充区域(Bottom padding)从MediaQuery开始,除了考虑SafeArea之外,还要考虑bottomNavigationBar的高度。

更详细地说:

@override
  Widget build(BuildContext context) {

    final bottomPadding = MediaQuery.of(context).padding.bottom; // From here you will get only SafeArea padding.

    return Scaffold(
      body: PageView(
        children: const [

          // But in build() method of each of these screens you will get
          // SafeArea padding with bottomNavigationBar height
          // just by calling MediaQuery.of(context).padding.bottom;

          FirstScreen(), 
          SecondScreen(),
          ThirdScreen(),
          FourthScreen(),

        ],
      ),
      bottomNavigationBar: MyBottomNavigationBar(),
    );
  }

5
当我使用底部导航栏BottomNavigationBar时,这个方法返回了0,对我来说并不是一个解决方案。请给出其他解决方法。 - lenz
所以我猜你做错了什么。你做的事情和我写的方式不同。 - Radomir Epur

1

我尝试了一下,对于安卓系统,我使用了kBottomNavigationBarHeight,而对于iOS系统,我认为高度是90像素。因此,我在我的常量文件中声明了高度,如下所示:double btmNavigationBarHeight = Platform.isAndroid ? kBottomNavigationBarHeight : 90;


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接