android - Flutter - 无法获取状态栏高度以准确计算可用屏幕高度
问题描述
我正在尝试创建一个在一列中包含 2 个小部件的测试应用程序。
第一个应该占据可用高度的 0.2,第二个应该占据可用高度的 0.8。后者是一个可滚动的小部件。
为了计算可用高度,我需要 3 个属性:屏幕高度、状态栏高度和应用栏高度。
我得到了屏幕高度和应用栏高度。
通过广泛的搜索,我应该能够使用 mediaQuery.padding.top 获得状态栏高度,但是它返回 0。知道为什么吗?
目前,底部溢出了 24 个像素,这显然是状态栏的高度。
var availableHeight = mediaQuery.size.height - mediaQuery.padding.top - appBar.preferredSize.height; //737 - 0 - 56
我正在 Windows 上的 android 模拟器中对其进行测试。设备:Pixel 3,操作系统:Android Pie。
我意识到我可以使用 LayoutBuilder 开箱即用地做到这一点,而无需手动计算可用高度,但我仍然对答案感兴趣。
这是完整的代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
AppBar appBar = AppBar(title: Text("Test"));
return MaterialApp(
title: 'Test App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: appBar,
body: SafeArea(child: Test(appBar))
)
);
}
}
class Test extends StatelessWidget {
final AppBar appBar;
Test(this.appBar);
Widget build(BuildContext context) {
var mediaQuery = MediaQuery.of(context);
var availableHeight = mediaQuery.size.height - mediaQuery.padding.top - appBar.preferredSize.height; //737 - 0 - 56
return Column(
children: <Widget>[
Container(
color: Colors.green,
height: availableHeight * 0.2,
),
Container(
height: availableHeight * 0.8,
child: getScrollable()
)
]
);
}
Widget getScrollable() {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
color: Colors.amber,
height: 600.0
),
Container(
color: Colors.red,
height: 600.0
),
],
)
);
}
}
解决方案
No need to calculate anything. Use Flex
and Flexible
to define how much space each child should take in relation to the space available:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
AppBar appBar = AppBar(title: Text("Test"));
return MaterialApp(
title: 'Test App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: appBar,
body: SafeArea(child: Test(appBar))
)
);
}
}
class Test extends StatelessWidget {
final AppBar appBar;
Test(this.appBar);
Widget build(BuildContext context) {
return Flex(
direction: Axis.vertical,
children: <Widget>[
Flexible(
flex: 2,
child: Container(
color: Colors.green,
),
),
Flexible(
flex: 8,
child: getScrollable(),
)
],
);
}
Widget getScrollable() {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
color: Colors.amber,
height: 600.0
),
Container(
color: Colors.red,
height: 600.0
),
],
)
);
}
}
推荐阅读
- python - 如何在 Python 中使用正则表达式捕获数字?
- javascript - html动态居中文本上下图像
- java - “java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'...'”是什么意思,我该如何解决?
- excel - 为什么类型转换不能解决这个 VBA 溢出错误
- android - RecyclerView 项目仅在添加时未对齐
- spring - 统一的二维弹簧效果
- android - 信标监控在 nativescript vue 中不起作用
- python - 导入的类看不到 Pytest 环境装置
- r - 我正在使用 rvest 抓取黄页,并在运行 submit_form() 时收到 403 Forbidden 消息
- python - 是否可以在线程中启动新进程?