Search code examples
c++fluttersystem-tray

Hide Application when outside the desktop application is clicked


I made an utility/tray application using flutter and i want it to hide when i click outside the application. How can we do this? I researched quite some time but i could not get the answer to this.

I looked out for window_manager, bitsdojo, googling, youtube and documentation. But could not get the answers.


Solution

  • You can use window_manager, which helps to find the focus.

    import 'package:flutter/cupertino.dart';
    import 'package:window_manager/window_manager.dart';
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> with WindowListener {
      @override
      void initState() {
        windowManager.addListener(this);
        super.initState();
      }
    
      @override
      void dispose() {
        windowManager.removeListener(this);
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        // ...
      }
    
     
      @override
      void onWindowFocus() {
        // do something when app gets into focus state
      }
    
      @override
      void onWindowBlur() {
        // do something when app gets into inactive/blur state
      }
    }