Flutter how to programmatically exit the app

In this article, We are going to see how to programmatically close a flutter application while pressing back press.exit(0): exit used to exit the mobile application. A sample video is below.


Using system navigator:
 SystemChannels.platform.invokeMethod('SystemNavigator.pop');
Using Exit:
 exit(0);

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio (File >new flutter project)


Step 2: Adding material package

Import method the runApp method in the main function call first while run the application.

 import 'package:flutter/material.dart';

 void main() {

     runApp(RunMyApp());

 }

Step 3: Creating a stateless widget

We can create a stateless widget that contains MaterialApp widget,AppBar,etc.

 class RunMyApp extends StatelessWidget {

     const RunMyApp({super.key});  

    @override

    Widget build(BuildContext context) {

    return MaterialApp(home);

     }

 }

Step 4: Final code 
 import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
runApp(HomeScreen());
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
void closeAppUsingSystemPop() {
SystemChannels.platform.invokeMethod('SystemNavigator.pop');
}
void closeAppUsingExit() {
exit(0);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: Text('Exit From the App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/company_logo.png'),
ElevatedButton(
onPressed: () {
closeAppUsingSystemPop();
},
child: Text('Exit using System Navigator')),
ElevatedButton(
onPressed: () {
closeAppUsingExit();
},
child: Text('Exit using Exit 0')),
],
)),
),
);
}
}

 

Step 5: Output of above example

Happy coding!


365Bloggy May 30, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive