flutter 如何修改 statusbar 的背景色?   2021-10-17


开发 todoline++ 项目, 第一个页面布局后, 遇到的问题是:
如何修改 statusbar 的背景色?
即, 如何修改 app 界面中电池图标所在的位置?

尝试的办法: 通过 appBar 的 backgroundColor 来修改

一阵狂搜后, 尝试的第一个办法是, 修改 appBar 的 backgroundColor, 代码如下:

1
2
3
4
5
6
appBar: AppBar(
elevation: 0.5,
brightness: Brightness.light,
backgroundColor: Colors.green,
// title: Text(widget.title),
),

确实, 背景色改变了, 但是出现我们意想不到的效果, 标题栏也出现了, 但在这个页面中, 我不想显示标题栏, 怎么办?

解决办法

又一阵狂搜后, 终于找到了解决办法, 在 build(BuildContext context) 对 SystemChrome.setSystemUIOverlayStyle 进行设置, 可以改变 android 界面中的 statusbar 背景色, 代码如下:

1
2
3
4
5
6
7
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
// systemNavigationBarColor: Colors.black,
statusBarColor: Colors.green
//color set to transperent or set your own color
)
);

但是 flutter 开发, 就是要考虑所有的平台, 上面的代码仅仅适用于 android, 但 IOS 呢?
前面尝试的办法中, 通过修改 appBar 的 backgroundColor 也能够实现, 只是他出现了副作用而已, 如果我们能够将标题栏隐藏掉, 那就可以了!

1
2
3
4
5
6
7
8
9
appBar: PreferredSize(
preferredSize: Size.zero,
//set your own hight for appbar.
child: AppBar(
elevation: 0,
brightness: Brightness.dark,
backgroundColor: Colors.green,
),
),

使用 PreferredSize 将 appBar 包起来, 然后设置 PreferredSize 为 0 就可以将标题栏隐藏掉!

可能遇到的错误 SystemChrome’ not defined in Flutter

import ‘package:flutter/services.dart’;

完整的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class _MyHomePageState extends State<UserRegister> {

@override
Widget build(BuildContext context) {
const double PERCENT_OF_WIDTH = 0.95;
const double PERCENT_OF_MARGIN_TOP = 0.30;

SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
// systemNavigationBarColor: Colors.black,
statusBarColor: Colors.green
//color set to transperent or set your own color
)
);

return Scaffold(
appBar: PreferredSize(
preferredSize: Size.zero,
//set your own hight for appbar.
child: AppBar(
elevation: 0,
brightness: Brightness.dark,
backgroundColor: Colors.green,
),
),
body: xxx,
);
}
}

来源

rrtutors.com/tutorials/how-to-change-status-bar-color-in-flutter


分享到:


  如果您觉得这篇文章对您的学习很有帮助, 请您也分享它, 让它能再次帮助到更多的需要学习的人. 您的支持将鼓励我继续创作 !
本文基于署名4.0国际许可协议发布,转载请保留本文署名和文章链接。 如您有任何授权方面的协商,请邮件联系我。

Contents

  1. 尝试的办法: 通过 appBar 的 backgroundColor 来修改
  2. 解决办法
  3. 可能遇到的错误 SystemChrome’ not defined in Flutter
  4. 完整的代码
  5. 来源