Issue
i am working on back button in my app but i face this issue in flutter
Thank so much in advanced
i am doing this before with this function but now it’s not working
i think because of null safty
sorry for my bad english
screenshot
here is my flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1110], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] VS Code (version 1.58.2)
[√] Connected device (3 available)
• No issues found!
here is my build method and Future function
Future<bool> _onBackPress() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('Exit From The App'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPress,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
brightness: Brightness.dark,
title: Text('Internet Availability Checker'),
),
),
);
}
Solution
In your _onBackPress()
function you are not returning a bool. It should be rewritten like this:
Future<bool> _onBackPress() async {
bool goBack = false;
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('Exit From The App'),
actions: [
TextButton(
onPressed: () {
goBack = false;
Navigator.pop(context);
},
child: Text('No'),
),
TextButton(
onPressed: () {
goBack = true;
Navigator.pop(context);
},
child: Text('Yes'),
),
],
);
},
);
return goBack;
}
Answered By – PatrickMahomes
Answer Checked By – Cary Denson (FlutterFixes Admin)