Flutter 沉浸状态栏和透明导航栏

开发环境:

Flutter (Channel master, 1.20.0-7.0.pre, on Mac OS X 10.14.5 18F132, locale zh-Hans-CN)
Android toolchain - develop for Android devices (Android SDK version 29.0.2)
Xcode - develop for iOS and macOS (Xcode 11.3.1)
Android Studio (version 4.0)

使用AndroidStudio新建一个Flutter Application工程

修改Android端

1.在launch_backgroud.xml中设置splash的背景图片

<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<item android:drawable="@android:color/black" />-->
    <!-- You can insert your own image assets here -->
    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/app_background" />
    </item>
</layer-list>

2.在styles.xml文件中添加导航栏透明的配置,必须在这里设置,在widget中设置会有问题,后面会说。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Theme applied to the Android Window while the process is starting -->
    <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
        <!-- Show a splash screen on the activity. Automatically removed when
             Flutter draws its first frame -->
        <!--在这里设置导航栏透明,不要在widget中设置-->     
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>
    <!-- Theme applied to the Android Window as soon as the process has started.
         This theme determines the color of the Android Window while your
         Flutter UI initializes, as well as behind your Flutter UI while its
         running.
         
         This Theme is only used starting with V2 of Flutter's Android embedding. -->
    <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
        <item name="android:windowBackground">@android:color/white</item>
    </style>
</resources>

3.注释掉AndroidManifest中的Normaltheme部分,如下图
Flutter 沉浸状态栏和透明导航栏_第1张图片
否则导航栏透明会直接显示splash的背景,可以透明,但是有问题如下图
Flutter 沉浸状态栏和透明导航栏_第2张图片

Flutter端设置

在main.dart中设置,必须在runApp方法后执行,否则无效
判断是否为苹果刘海屏的方法非常简单,在Flutter中判断即可,无需对IOS代码进行操作

if (defaultTargetPlatform == TargetPlatform.android) {
    
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarBrightness: Brightness.dark,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  } else if (defaultTargetPlatform == TargetPlatform.iOS) {
    //手机的状态栏默认为打开的
    //判断是否为苹果手机。如果是,并且padding top不为0即为x系列
    //其他系列关闭状态栏
    if (MediaQuery.of(context).padding.top == null ||
        MediaQuery.of(context).padding.top == 0) {
      SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
    }
  }

至此,只能说是基本实现了沉浸状态栏和透明导航栏。因为还有一个问题
就是打开app的第一屏的状态栏没有透明,导航栏的虽然透明了,但是图标应该为light。可以尝试对app样式进行全屏设置。后续研究一下。再更新

你可能感兴趣的:(Flutter)