😑

WidgetsBindingObserver.didChangeAppLifecycleState が not called…

2021/10/12に公開

Flutter でアプリの Lifecycle を検知したいときのために

https://api.flutter.dev/flutter/widgets/ClipboardStatusNotifier/didChangeAppLifecycleState.html

が用意されている。

ほうほう。

class HomeScreenView extends StatefulWidget {
  
  _HomeScreenViewState createState() => _HomeScreenViewState();
}

class _HomeScreenViewState extends State<HomeScreenView> with WidgetsBindingObserver {
  
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
  }

  
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // Write you code here.
  }
}

が… うんともすんとも言わない。Why FLUTTER ??

super.didChangeAppLifecycleState(state) へ飛んでみる。

/// Called when the system puts the app in the background or returns
/// the app to the foreground.
///
/// An example of implementing this method is provided in the class-level
/// documentation for the [WidgetsBindingObserver] class.
///
/// This method exposes notifications from [SystemChannels.lifecycle].
void didChangeAppLifecycleState(AppLifecycleState state) { }

うん?

This method exposes notifications from [SystemChannels.lifecycle].

プロジェクト内でコード検索すると、他の箇所で

SystemChannels.lifecycle.setMessageHandler((message) async {
  // ~~~
});

と、SystemChannels.lifecycle へ直接 Handler を追加しているところがあった。。。
で、これを止めてみると、HomeScreenViewdidChangeAppLifecycleState が呼ばれました🎉🎉🎉 これはハマった…

Flutter: 2.5.2
Dart: 2.14.3
Engine: revision 6ac856380f

Discussion