沉浸式状态栏,在Android开发中是一个比较麻烦的地方,因为不同的机型和版本兼容问题太多了,API变化也快,但是到了Flutter,一切问题都解决了,因为整个区域都是Skia绘制的,要什么都行,随便来。

以上问题只针对Android,因为iOS没这问题。。。默认就是沉浸式,只能说,Google的设计师,真是不懂行情。

我们来看下iOS的效果。

FlutterComponent最佳实践之沉浸式 - 图1

没什么好适配的,干就完了了。

状态栏沉浸式

再来看看Android。

FlutterComponent最佳实践之沉浸式 - 图2

这个状态栏,为什么国内的设计师都想干掉它的颜色呢。

首先,我们来修改状态栏的颜色,Flutter提供了SystemChrome.setSystemUIOverlayStyle来修改状态栏和底部导航栏的样式修改,借助它,我们可以很方便的干掉状态栏的默认颜色。

  1. SystemChrome.setSystemUIOverlayStyle(
  2. const SystemUiOverlayStyle(
  3. statusBarColor: Colors.transparent,
  4. statusBarBrightness: Brightness.light,
  5. ),
  6. );

很简单,设置状态栏为透明即可,不过有一点需要注意,那就是statusBarBrightness,如果你后面有用AppBar组件,那么statusBarBrightness需要在AppBar中设置,否则这里的设置会被覆盖而不生效。

FlutterComponent最佳实践之沉浸式 - 图3

既然可以设置成透明,那么当然还可以设置成其它任何你想要的颜色,这里就不演示了。

AppBar沉浸式

下面再来看看AppBar的沉浸式设置,它给我们提供了backgroundColor的设置,我们只需要把默认的elevation干掉即可。

return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
    backgroundColor: Colors.transparent,
    elevation: 0,
  ),

但是,效果居然是这样?

FlutterComponent最佳实践之沉浸式 - 图4

没错,因为你还缺少了关键的一步,那就是设置Scaffold的extendBodyBehindAppBar属性。

return Scaffold(
  extendBodyBehindAppBar: true,
  appBar: AppBar(
    title: Text(widget.title),
    backgroundColor: Colors.transparent,
    elevation: 0,
  ),

这样就可以实现AppBar的沉浸式了。

FlutterComponent最佳实践之沉浸式 - 图5

ListView的沉浸式

我们把AppBar也干掉,因为有时候我们需要自己来实现AppBar,所以,来看下ListView的沉浸式。

return Scaffold(
  body: Container(
    color: Colors.yellow,
    child: ListView(
      children: List.generate(
        100,
        (index) => TextButton(
          onPressed: () {},
          child: Text('$index'),
        ),
      ),
    ),
  ),

效果差不多,但是为什么顶部有坑?

FlutterComponent最佳实践之沉浸式 - 图6

这是因为ListView在这种场景下,很「智能」的给自己顶部加了默认的padding。我们去掉这个padding就可以了。

return Scaffold(
  body: Container(
    color: Colors.yellow,
    child: ListView(
      padding: const EdgeInsets.only(top: 0),
      children: List.generate(
        100,
        (index) => TextButton(
          onPressed: () {},
          child: Text('$index'),
        ),
      ),
    ),
  ),

这样就完美了。

FlutterComponent最佳实践之沉浸式 - 图7

其它

为了给Android开小灶,我们还得给它加上设备的判断。

if (Platform.isAndroid) {

}

除了通过SystemChrome.setSystemUIOverlayStyle设置以外,Flutter也提供了AnnotatedRegion来设置,效果是一样的。

return AnnotatedRegion<SystemUiOverlayStyle>(
  value: const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarBrightness: Brightness.light,
  ),
  child: Scaffold(

向大家推荐下我的网站 https://xuyisheng.top/ 专注 Android-Kotlin-Flutter 欢迎大家访问

FlutterComponent最佳实践之沉浸式 - 图8