How do I check if the Flutter application is in the foreground or not?

前端 未结 4 1405
情深已故
情深已故 2020-12-29 22:46

I don\'t want to show notification when the app is in foreground. How can I check live state of my app?

4条回答
  •  滥情空心
    2020-12-29 22:51

    Simply create a bool variable which will keep track of all your background/foreground stuff.

    Full code:

    class _HomePageState extends State with WidgetsBindingObserver {
      // This variable will tell you whether the application is in foreground or not. 
      bool _isInForeground = true;
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
      
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);
        _isInForeground = state == AppLifecycleState.resumed;
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) => Scaffold();
    }
    

提交回复
热议问题