在上一節(改變 TabBar 背景顏色的方法)中有發現的一個問題:在 iPhone X 等劉海屏手機中,會出現頁面被導航欄或者底部黑線遮擋的問題:
解決辦法有兩種:
-
使用以下代碼獲取手機狀態欄和底部黑線的高度,然後設置 Widget 的 Padding 或者 Margin:
//獲取狀態欄高度(上邊距) final double topPadding = MediaQuery.of(context).padding.top; //獲取下邊黑線高度(下邊距) final double bottomPadding = MediaQuery.of(context).padding.bottom;
-
使用 SafeArea(推薦),直接在外面包一層這個 Widget:
class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin { TabController _tabController; @override void initState() { super.initState(); _tabController = TabController(length: 3, vsync: this); } @override Widget build(BuildContext context) { return Scaffold( //使用 SafeArea 適配 iPhone X 等劉海屏不規則手機 bottomNavigationBar: SafeArea( //使用 Material 改變 TabBar 背景色 child: Material( color: Colors.blue, child: TabBar( ... ), ), ), body: TabBarView( ... ), ); } }