Flutter Android端启动白屏

6,606 阅读1分钟

问题描述

Flutter 应用在 Android 端上启动时会有一段很明显的白屏现象,白屏的时长由设备的性能决定,设备性能越差,白屏时间越长。

问题分析

其实启动白屏的问题在Android原生应用上也是一个常见问题,大致是因为从用户点击 Launcher Icon 到应用首页显示之间,Android 系统在完成应用的初始化工作,其流程如下:

在 Flutter Android 端上,白屏的问题会更加严重,因为除了 Android 应用启动耗时外,还增加了 Flutter 初始化耗时。
直到 Flutter 渲染出第一帧内容,用户才能感知到App启动完成。

解决方案

解决方案很简单,Android原生的白屏问题可以通过为 Launcher Activity 设置 windowBackground 解决,而 Flutter 也是基于此办法,同时优化了 Flutter 初始化阶段的白屏问题(覆盖一个launchView),只用两步设置便能解决 Flutter 中白屏问题。

  1. 在项目的 android/app/src/main/res/mipmap-xhdpi/ 目录下添加闪屏图片;
  2. 打开 android/app/src/main/res/drawable/launch_background.xml 文件,这个文件就是闪屏的背景文件,具体如何设置可以查阅 Android Drawable,我在 demo 中的设置如下:
<?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/background_dark" />

    <!-- You can insert your own image assets here -->
    <item
        android:bottom="84dp">
        <bitmap
            android:src="@mipmap/launch_image" />
    </item>
</layer-list>

效果对比

启动白屏 启动白屏优化

Flutter练习项目

github.com/zh8637688/F…