2

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

Amol Gangadhare
  • 1,059
  • 2
  • 11
  • 24
  • Not sure if it would work but you could try something like [this](https://stackoverflow.com/a/60186171/13625305) – dev-aentgs Jul 27 '20 at 13:53

3 Answers3

4

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

lijy91
  • 311
  • 4
  • 3
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.

smorgan
  • 20,228
  • 3
  • 47
  • 55
0

You can use this package bitsdojo_window and in this button, CloseWindowButton(colors: closeButtonColors), you can add an onPressed callback that give you complete control to launch a dialog, or run clean up code before calling appWindow.close()

Dharman
  • 30,962
  • 25
  • 85
  • 135
Karl
  • 101
  • 1