How to handle onPause/onResume in Flutter App?

主宰稳场 提交于 2019-12-04 10:26:53

问题


I'm new to Dart/Flutter and would like to build a simple app where a LinearProgressBar gets updated every second.

Without getting too much into the actual code, I have the following setup working.

  • A function that calculates the progress, based on passed time.
  • A LinearProgressBar showing the progress.
  • A periodic Timer recalculating the progress and updating the progress bar every second.
  • I debugprint 'tick' every time, the recalculation is done.

Everything is working as expected with one exception. The 'tick' keeps getting printed when I move the app in the background on my Android device.

On native Android, I would cancel my periodic Timer when the 'onPause' event is triggered.

Is there something similar in Flutter? All I could find was 'initState' and 'dispose'. Dispose, however, does not get called when moving the app to background.

I don't want the timer to keep ticking in the background.

On my research, I found this Stack Overflow question onresume-and-onpause-for-widgets-on-flutter. It's answer suggests using TickerProviderStateMixin.

I used it the following way.

class _BarItemState extends State<BarItem> with SingleTickerProviderStateMixin {
    Ticker ticker;
    num progress = 1.0;

    @override
    void initState() {
       super.initState();
       ticker = createTicker((duration) => setState(() {
          debugPrint('tick');
          progress = duration.inSeconds / 30;
       }))
      ..start();
    }

    // other stuff omitted

}

It is working, but I'm still not satisfied.

The reason is, that the ticker callback is getting now called every few milliseconds instead of once a second. This seems to me like a waste of resources (I don't need a smooth animation), ... am I overcomplicating things?

Even if it seems that I don't need it for my use case, I still would like to know:

How to handle the onPause/onResume events on my own?


回答1:


You can override the didChangeAppLifecycleState of the WidgetBindingObserver interface to receive notifications for app lifecycle changes.

There's sample code in this page




回答2:


You can use lifecycle channel from SystemChannels.

Example:

SystemChannels.lifecycle.setMessageHandler((msg){
  debugPrint('SystemChannels> $msg');
});

Output:

I/flutter ( 3672): SystemChannels> AppLifecycleState.paused
I/flutter ( 3672): SystemChannels> AppLifecycleState.resumed


来源:https://stackoverflow.com/questions/47250308/how-to-handle-onpause-onresume-in-flutter-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!