This is the updated code
basically, WillPopScope -> onWillPop works on the future argument
we can say as when it happens then ????
so as soon the back button is pressed WillPopScope -> onWillPop gets activated and listens to the argument more specific the back button event to pop it (replace it)
Most of the time I use it to show a DialogBox of Future type because it will only appear when it is needed same can be used to navigate to a new screen as well (hope so) preferred to do MaterialPage routing or named routing techniques for navigation,
use WillPopScope for the hardware back button event listening (hardware = Android/IOs) to show the exit popup
code is already been given above but does not work for me so I change a little bit
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async{
return _moveToScreen2(context);
},
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
_moveToScreen2(context);
}),
title: Text("Screen 1"),
),
),
);
}
Future<bool>_moveToScreen2(BuildContext context) =>
Navigator.pushReplacementNamed(context, "screen2");
===============================================
What I do on Exit
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: ()=> showExitPopup(context)
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("Screen 1"),
),
),
);
}
=========================================
On Back button Press
created a dart file with the name showExitPopup
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:vexpositions/Servises/ConstantManager.dart';
Future<bool> showExitPopup(context) async{
return await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: SizedBox(
height: 90,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("Want to Exit the app!"),
const SizedBox(height:20),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
print('yes selected');
exit(0);
},
style: ElevatedButton.styleFrom(
primary: Colors.white),
child: const Text("Yes", style: TextStyle(color:
Colors.black)),
),
),
const SizedBox(width: 15),
Expanded(
child: ElevatedButton(
onPressed: () {
print('no selected');
Navigator.of(context).pop();
},
style: ElevatedButton.styleFrom(
primary: Colors.red.shade800,
),
child: const Text("No", style: TextStyle(color:
Colors.white)),
))
],
)
],
),
),
);
});
}