Search code examples
flutter

Closing flutter web app (flutter PWA) by clicking on a button


I create a flutter web app and use it as a PWA in my java-script website I opened it using iframe.

I want to close my PWA by tapping on a button by SystemChannels.platform.invokeMethod('SystemNavigator.pop').

I tried this code but not working:

GestureDetector(
  onTap: () {
    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  },
  child: Container(padding: const EdgeInsets.all(4), child: Icon(Icons.close, color: BpColors.white, size: 20)),
);

I also tried using exit(0) but it makes the website to go to previous page not just closing the PWA.


Solution

  • This worked for me

    close_clicked is the event name that my javascript is listening to.

    import 'dart:html' as html;
    
    import 'package:flutter/material.dart';
    
    
    class GlobalCloseButton extends NoControllerWidget {
      const GlobalCloseButton({super.key});
    
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: () {
            html.window.parent?.postMessage("close_clicked", "*");
          },
          child: Container(padding: const EdgeInsets.all(4), child: Icon(Icons.close, color: Colors.red, size: 20)),
        );
      }
    }