Flutter desktop: How to catch closure button?

1,259

Solution 1

window_manager now supports this.

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);
    _init();
    super.initState();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  void _init() async {
    // Add this line to override the default close handler
    await windowManager.setPreventClose(true);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // ...
  }

  @override
  void onWindowClose() async {
    bool _isPreventClose = await windowManager.isPreventClose();
    if (_isPreventClose) {
      showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            title: Text('Are you sure you want to close this window?'),
            actions: [
              TextButton(
                child: Text('No'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              TextButton(
                child: Text('Yes'),
                onPressed: () {
                  Navigator.of(context).pop();
                  await windowManager.destroy();
                },
              ),
            ],
          );
        },
      );
    }
  }
}

https://github.com/leanflutter/window_manager#confirm-before-closing

Solution 2

There is currently no built-in hook that lets you handle window close attempts; see this issue. You'd need to implement it yourself by adding a WM_CLOSE handler to win32_window.cpp, canceling the close, calling into Dart with a MethodChannel (or another similar mechanism), and then if the response from Dart indicates the window should be closed, destroying it directly.

Share:
1,259
Fagnola Romain
Author by

Fagnola Romain

Updated on December 12, 2022

Comments

  • Fagnola Romain
    Fagnola Romain over 1 year

    I'm working on a desktop application with flutter (Windows), I need to set up an AlertDialog if the user tries to close the window with the close button.

    If someone has an idea or even a solution, I'll take it :D

    I have attached a reference image below.

    This button

    • dev-aentgs
      dev-aentgs almost 4 years
      Not sure if it would work but you could try something like this