I don't see that being implemented in the default app template on macOS. When I pressed Command W, it does nothing. How can we do that in flutter?
CodePudding user response:
Note: For exiting a window on mac, you need to press command Q, this approach is if you want to specifically detect command W.
To exit a Flutter app (not for IOS), you can call:
SystemNavigator.pop();
which, if you take a look internally at its code, calls:
SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop'
So, to detect Command W you can setup a keyboard listener:
RawKeyboard.instance.addListener((key) {
if (key.isMetaPressed && key.isKeyPressed(LogicalKeyboardKey.keyW)) {
SystemNavigator.pop();
}
});
Complete code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(home: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
RawKeyboard.instance.addListener((key) {
if (key.isMetaPressed && key.isKeyPressed(LogicalKeyboardKey.keyW)) {
SystemNavigator.pop();
}
});
return Scaffold(
body: Text("Press on the command w key to close the app"),
);
}
}