androidflutterfunctionexiticonbutton

Exit application on press of IconButton in Flutter


How to permanently exit the application from IconButton in AppBar? I set icon:

return Scaffold(
            appBar: AppBar(
              title: const Text('Your app'),
              actions: [
                IconButton(
                  icon: const Icon(
                    Icons.exit_to_app,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    context.read<HomeCubit>().closeAppUsingSystemPop();
                  },
                )
              ],
            ),

and in Home_Cubit I have:

 void closeAppUsingSystemPop() {
    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

After pressing the icon, it exits the application, but only once and stays in memory.

I would like the app to close completely when I press the icon.


Solution

  • But don't use SystemNavigator.pop() for iOS, Apple says that the application should not exit itself :)

    Below code will work on Android for both cases,I hope this helps.

    if (Navigator.canPop(context)) {
         Navigator.pop(context);
       } else {  
       SystemNavigator.pop();
    }