2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutterアプリでバックグラウンド移行とフォアグラウンドに戻った際の状態変化を検知する

Posted at

はじめに

本記事ではFlutterアプリで WidgetsBindingObserver を使用して、アプリがバックグラウンド状態に移行したときと、フォアグラウンド状態に戻ったときの状態変化を検知し、それぞれログを出力する方法について記載します。

環境

  • Flutter 3.22.1
  • vscode

ソース

アプリのライフサイクルが変化するたびに、didChangeAppLifecycleStateでそれを検知します。
下記のソースではバックグラウンド状態になった時と、フォアグラウンド状態に戻った時にログをコンソールに出力します。

main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  // Widget生成時
  void initState() {
    super.initState();
    // 監視の開始を登録
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  // Widget破棄時
  void dispose() {
    // 監視の終了を登録
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // ライフサイクルの状態が変化した時に呼び出される
    if (state == AppLifecycleState.resumed) {
      // フォアグラウンド状態に戻った時の処理
      print('フォアグラウンド状態に戻りました');
    } else if (state == AppLifecycleState.paused) {
      // バックグラウンド状態に移行した時の処理
      print('バックグラウンド状態になりました');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('サンプルタイトル'),
      ),
      body: Center(
        child: Text(
          'サンプル画面',
          style: TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}

参考

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?