6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

flutter hooks で簡単に画面復帰時処理などのアプリライフサイクルを管理する

Last updated at Posted at 2022-08-11

やりたいこと

アプリがバックグラウンドから画面復帰した時などに処理を行いたい。
Swift での AppDelegate 的な。
それを flutter_hookshooks_riverpod を使っており HookConsumerWidget で実装したい場合について。

環境

flutter_hooks: ^0.18.4
hooks_riverpod: ^1.0.3

実装

最近このアプリライフサイクルを管理する useOnAppLifecycleStateChange が公式に追加された。非常に簡単。


class TestView extends HookConsumerWidget {
  const TestView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // これ
    useOnAppLifecycleStateChange((beforeState, currState) {
      switch (currState) {
        case AppLifecycleState.resumed:
          debugPrint('LOG: バックグラウンドから復帰しました');
          break;
        case AppLifecycleState.inactive:
          debugPrint('LOG: バックグラウンドになりました');
          break;
        case AppLifecycleState.paused:
          debugPrint('LOG: 一時停止しました');
          break;
        case AppLifecycleState.detached:
          debugPrint('LOG: 終了しました');
          break;
      }
    });

    return const Scaffold(
      body: Center(
        child: Text('test'),
      ),
    );
  }
}

画面収録.gif

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?