Photo by Hilthart Pedersen on Unsplash
はじめに
Flutterでアプリが復帰した時やサスペンドした時を検出して任意の処理を実行するための手順をまとめます。
前提と環境
以下の通りです。
- Flutter 1.9.1
- Dart 2.5.0
WidgetsBindingObserverについて
ミックスインとしてWidgetsBindingObserver
を使うことでアプリのライフサイクル(復帰、サスペンド等)を検出するメソッドであるdidChangeAppLifecycleState
を使用できるようになります。なお、ライフサイクル以外にも、そのアプリが動作するスマートフォンの言語設定の変更やスマートフォンの向き(縦か横か)の変更を検出するメソッドも用意されています。詳細については以下の公式ドキュメントに記載されています。
Interface for classes that register with the Widgets layer binding.
When used as a mixin, provides no-op method implementations.
WidgetsBindingObserverでアプリのライフサイクルを検出する
以下のようにWidgetsBindingObserver
をミックスインで使います。
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {...}
また、initState
とdispose
でWidgetsBindingObserver
の初期化と破棄を記述します。
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if(state == AppLifecycleState.resumed){
// アプリが復帰した(resumed)時に実行したい処理;
}
}
@override
Widget build(BuildContext context) {
// 省略
そして上記のようにdidChangeAppLifecycleState
を使用してアプリのライフサイクルがどの状態であるかを検出し、復帰、サスペンド等に合わせて処理を記述することができます。
didChangeAppLifecycleState
は、アプリがバックグランドに移行した直後、フォアグラウンドに移行した直後に実行されます。
上記はアプリが復帰時(resumed
)に処理を実行していますが、他にもinactive
(非アクティブ、iOSとAndroidで挙動が異なる)、paused
(一時停止)、suspending
(Androidのみ)を検出できます。
したがって、以下のように各状態に合わせて実行する処理を分岐させることができます。
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if(state == AppLifecycleState.inactive){
print('inactive');
}else if(state == AppLifecycleState.resumed){
print('resumed');
}else if(state == AppLifecycleState.paused){
print('paused');
}else if(state == AppLifecycleState.suspending){
print('suspending');
}
}
なお、それぞれのライフサイクルの状態はiOSとAndroidで若干異なります。AppLifecycleState
で使用できる値とiOSとAndroidでの挙動の違いの説明は以下の公式ドキュメントに記載されています。
The values below describe notifications from the operating system. Applications should not expect to always receive all possible notifications.
Android実機で確認したところ、アプリを開いている状態でホームボタンを押してホームに戻るとinactive
とpause
が共に検出され、ホームからアプリに戻るとinactive
とresume
の両方が検出されました。
想定しているアプリの使用方法に基づいてそれぞれ実機で確認したほうが良さそうです。
まとめ
Flutterでアプリの復帰、サスペンドなどのライフサイクルを検出して処理を実行する方法をまとめました。iOSとAndroidで挙動が異なると公式ドキュメントに記載されているので、少し注意が必要そうです。
SPONSORED LINK