我如何在Flutter中获取Scaffold
的BottomNavigationBar
的高度?我知道使用MediaQuery.of(context).size
可以获取屏幕大小。是否有类似于BottomNavigationBar
的方法?
我如何在Flutter中获取Scaffold
的BottomNavigationBar
的高度?我知道使用MediaQuery.of(context).size
可以获取屏幕大小。是否有类似于BottomNavigationBar
的方法?
Container(
width: MediaQuery.of(context).size.width,
height: kBottomNavigationBarHeight,
child: Scaffold(
backgroundColor: Colors.transparent,
body: null,
bottomNavigationBar: BottomNavigationBar()
)
)
这将创建一个只有足够空间容纳BottomNavigationBar小部件的脚手架。
kBottomNavigationBarHeight是一个常量,可以在constants.dart文件中找到。
您可以使用key
字段来获取小部件的大小。
final key = GlobalKey();
... set key field of widget
double height = key.currentContext.size.height;
如果您想知道在带有底部导航栏的主脚手架中的子屏幕中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(),
);
}
BottomNavigationBar
时,这个方法返回了0,对我来说并不是一个解决方案。请给出其他解决方法。 - lenz我尝试了一下,对于安卓系统,我使用了kBottomNavigationBarHeight
,而对于iOS系统,我认为高度是90像素
。因此,我在我的常量文件中声明了高度,如下所示:double btmNavigationBarHeight = Platform.isAndroid ? kBottomNavigationBarHeight : 90;
kBottomNavigationBarHeight
是一个常量,但它未考虑到在没有Home键的iPhone或使用最新导航栏的Android设备上可能存在SafeArea
填充的情况。 - Christopher Boyd