この記事で紹介すること
Flutter Webでは初回のローディングがとても長いという致命的な問題があります。
実際に初回デプロイ後に確認した際に体感では、ブラウザ自体のローディング完了後に真っ白な画面が5秒以上表示されていた体感があります。
本記事では、その真っ白なローディング画面に対応するためにLottieを利用していい感じのローディングアニメーションを表示させる方法を紹介します。
作成物
実装方法
1. web/index.html
のタグ内にLottie Playerのスクリプトと.loading
用のスタイルを追加する
web/index.html
<!-- これより上省略 -->
<!-- Lottie animation -->
<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
<script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>
<style>
.loading {
display: flex;
justify-content: center;
align-items: center;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
</head>
2. web/index.html
の<body>
タグの最下部に.loading
のdivタグとLottieアニメションを表示するコードを追加する
web/index.html
<!-- これより上省略 -->
<div class="loading">
<dotlottie-player src="{ここにlottieのアニメーションのURL}" background="transparent" speed="1" style="width: 300px; height: 300px;" loop autoplay></dotlottie-player>
</div>
</body>
3. ロード完了後に.loadingのdivを消す処理を追加
トップ画面のinitState function
import 'dart:html';
@override
void initState() {
super.initState();
// くるくるがあれば除去する
final loading = querySelector('.loading') as DivElement?;
if (loading != null) loading.remove();
}
参考記事