How to implement a Method Channel in Flutter to handle system sleep events on macOS

45 Views Asked by At

I implemented this observer to trigger a function when the screen of my MacOS application is in sleep mode:

macOS/AppDelegate.swift

import Cocoa
import FlutterMacOS

@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
    
    override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
    
    override func applicationDidFinishLaunching(_ aNotification: Notification) {

        NSWorkspace.shared.notificationCenter.addObserver(self,
                                                          selector: #selector(didSleep),
                                                          name: NSWorkspace.screensDidSleepNotification,
                                                          object: nil)
        
        
        
    }
    
    @objc func didSleep(notification: NSNotification) {
        print("sleep")
    }
}

How can I create a flutter method channel or event channel to get this notification when my "didSleep" function in Swift is called? Or what are the next steps?

I'm not familiar with these native code implementations and I couldn't find any documentation to call a function only when the observer triggers the function.

Thanks in advance for your help!

0

There are 0 best solutions below