Flutter Alert dialog is not showing when I debug on chrome - flutter

When I debug on chrome the alert dialog is not showing.
My code:
PopupMenuItem(
value: 1,
onTap: () {
ShowMyDialog();
Navigator.pop(context);
},
child: ListTile(
leading: Icon(Icons.edit),
title: Text("Edit"),
),
),
Future<void> ShowMyDialog() async {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Update"),
content: Container(
child: TextField(
controller: editingController,
),
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Cancel"),
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Update"),
),
],
);
},
);
}

Pass context to ShowMyDialog() method. like ShowMyDialog(context);

onTap: () {
ShowMyDialog();
Navigator.pop(context);
},
to
onTap: () {
ShowMyDialog();
},
You were popping the context as soon as the Dialog open so it wasn't showing on that time . now try with this

Related

How to close severals showDialogs in flutter

How can I to close all the showDialogs in my aplication? in this case _mostrarDialogConfirmacion is the dialog where i request to the user a confirmation to make a query, cargandoDialog is another dialog where i show a loading message while the query is executing, when the query finish, i want to close the two dialogs and only see the _mostrarDialogMensaje dialog
_mostrarDialogConfirmacion(
mensaje,
BuildContext context,
codLink,
motivo,
) {
return showDialog(
context: context,
builder: (context){
return AlertDialog(
title: const Text(
'Informacion',
textAlign: TextAlign.center,
),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget> [
Text(mensaje, textAlign: TextAlign.center),
],
),
actions: <Widget> [
TextButton(
onPressed: () async {
Navigator.of(context).pop();
cargandoDialog(context);
List<dynamic> ingresarReclamo1 = await ingresarReclamo
.ingresarReclamo(codLink, titular, motivo);
// ignore: use_build_context_synchronously
Navigator.of(context).pop();
// ignore: use_build_context_synchronously
_mostrarDialogMensaje(
ingresarReclamo1[0].observaciones,
ingresarReclamo1[0].validado,
context,
);
},
child: const Text('Si')
),
TextButton(
onPressed: ()=> Navigator.of(context).pop(),
child: const Text('No')
),
],
);
}
);
}
you will dismiss first dialog and then you can use whenComplete to dismiss the second dialog
showDialog(
.....
).whenComplete(() => Navigator.of(context).pop())
You can return bool while .pop(boolValue) to check the tap button. Also, the showDialog is a future method, you can use await until it finished and then processed to next dialog. Navigator.of(context).pop() will be used to close recent dialog on this case. As for my understanding about the question, try this example code.
_mostrarDialogConfirmacion(mensaje, BuildContext context, codLink, motivo) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: const Text('Informacion', textAlign: TextAlign.center),
content: Column(
mainAxisSize: MainAxisSize.min,
),
actions: <Widget>[
TextButton(
onPressed: () async {
// Navigator.of(context)
// .pop(); //if you like to close previous one before showing the next dialog
final bool isSi = await showDialog(
barrierDismissible: false,
builder: (context) => AlertDialog(
content: Text("Second Dialog"),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('Si')),
TextButton(
onPressed: () =>
Navigator.of(context).pop(false),
child: const Text('No')),
],
),
context: context);
if (mounted && isSi) {
Navigator.of(context).pop();
await showDialog(
builder: (context) => AlertDialog(
content: Text("_mostrarDialogMensaje")),
context: context);
}
},
child: const Text('Si')),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('No')),
],
);
});
}

Flutter Alert Dialog doesn't work/displaying

So I am facing this problem that my alert Dialog isn't displaying. I had tried every possible solution and searching here and there but nothing works. When I click on the edit button from the pop up menu nothing is displayed everything remains the same.
Calling alert Dialog
trailing: PopupMenuButton(
icon: Icon(Icons.more_vert),
itemBuilder: (context)=>[
PopupMenuItem(
value:1,
onTap: (){
//debugPrint('popup');
Navigator.pop(context);
_showMyDialog();
},
child: ListTile(
leading: Icon(Icons.edit),
title: Text('Edit'),
)),
PopupMenuItem(
value:1,
// onTap: (){
// Navigator.pop(context);
// showDialogBox();
// },
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Delete'),
)),
]),
Alert Dialog Code
Future<void> showDialogBox(String title)async{
editController.text=title;
debugPrint('dialog');
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
debugPrint('alert');
return AlertDialog(
title: Text('Update'),
content: Container(
child: TextFormField(
controller: editController,
),
),
actions: [
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Update')),
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Cancel')),
],
);
}
);
}
Complete Class Code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:firebase_tutorial/utils/routes/routes_names.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_database/firebase_database.dart';
import '../../utils/utils.dart';
class PostScreen extends StatefulWidget {
const PostScreen({Key? key}) : super(key: key);
#override
State<PostScreen> createState() => _PostScreenState();
}
class _PostScreenState extends State<PostScreen> {
final ref=FirebaseDatabase.instance.ref('Post');
FirebaseAuth _auth=FirebaseAuth.instance;
final searchController=TextEditingController();
final editController=TextEditingController();
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: ()async{
SystemNavigator.pop();
return true;
},
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Post Screen'),
actions: [
GestureDetector(
onTap: (){
_auth.signOut().then((value){
Navigator.pushNamed(context, RoutesNames.loginScreen);
}).onError((error, stackTrace){
Utils().toastMessage(error.toString());
});
},
child: Icon(Icons.logout_outlined)),
SizedBox(width: 10,),
],
),
floatingActionButton: FloatingActionButton(
onPressed:(){
Navigator.pushNamed(context, RoutesNames.newPost);
},
child: Icon(Icons.add),),
body: Column(
children: [
// Expanded(
// child:FirebaseAnimatedList(
// query: ref,
// itemBuilder: (context,snapshot,animation,index){
// return ListTile(
// title: Text(snapshot.child('post').value.toString()),
// );
// }
// ),
// ),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextFormField(
onChanged: (String value){
setState(() {
});
},
controller: searchController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: "Search",
),
),
),
Expanded(child: StreamBuilder(
stream: ref.onValue,
builder: (context,AsyncSnapshot<DatabaseEvent> snapshot){
if(!snapshot.hasData){
return CircularProgressIndicator();
}
else{
return ListView.builder(
itemCount: snapshot.data!.snapshot.children.length,
itemBuilder: (context,index){
Map<dynamic,dynamic> map=snapshot.data!.snapshot.value as dynamic;
List<dynamic> list=[];
list.clear();
list=map.values.toList();
final title=list[index]['post'].toString();
if(searchController.text.isEmpty){
return ListTile(
title: Text(list[index]['post']),
subtitle: Text(list[index]['id'].toString()),
trailing: PopupMenuButton(
icon: Icon(Icons.more_vert),
itemBuilder: (context)=>[
PopupMenuItem(
value:1,
onTap: (){
//debugPrint('popup');
Navigator.pop(context);
_showMyDialog();
},
child: ListTile(
leading: Icon(Icons.edit),
title: Text('Edit'),
)),
PopupMenuItem(
value:1,
// onTap: (){
// Navigator.pop(context);
// showDialogBox();
// },
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Delete'),
)),
]),
);
}
else if(title.toLowerCase().contains(searchController.text.toLowerCase())){
return ListTile(
title: Text(list[index]['post']),
subtitle: Text(list[index]['id'].toString()),
);
}
else{
return Container();
}
});
}
}))
],
),
),
);
}
Future<void> showDialogBox(String title)async{
editController.text=title;
debugPrint('dialog');
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
debugPrint('alert');
return AlertDialog(
title: Text('Update'),
content: Container(
child: TextFormField(
controller: editController,
),
),
actions: [
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Update')),
TextButton(onPressed: (){
Navigator.pop(context);
}, child: Text('Cancel')),
],
);
}
);
}
}
try adding a delay before calling showDialog like this:
await Future.delayed(const Duration(milliseconds: 10));
Your dialog isnt displayed because when you select a menu item the pop() method is automatically called to close the popup menu; so if you open a dialog immediately, the dialog will get automatically popped.
hope this fixes your issue

How to open an AlertDialog in Flutter by Button-Press?

after Button-press, i want to open an AlertDialog, but only if the variable bool showAlert is true.
This is my code until now:
FlatButton(
child: Text("HIER"),
onPressed: () {
return AlertDialog(
title: Text("HI"),
content: Text("Are you there?"),
actions: [
FlatButton(child: Text("Yes"), onPressed: () {},),
FlatButton(child: Text("No"), onPressed: () {},)
],
elevation: 24,
);
},
),
For my question (opening the alert if bool is true), the problem is, the AlertDialog is not opening.
Any solutions? Thanks
To show an AlertDialog you need a showDialog, so the code results like this :
FlatButton(
child: Text("HIER"),
onPressed: () {
if(showAlert){
showDialog(
//if set to true allow to close popup by tapping out of the popup
barrierDismissible: false,
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text("HI"),
content: Text("Are you there?"),
actions: [
FlatButton(child: Text("Yes"), onPressed: () {},),
FlatButton(child: Text("No"), onPressed: () {},)
],
elevation: 24,
),
);
}
},
),
Use this code to show native diolog depends on platform:
FlatButton(
child: Text("HIER"),
onPressed: () {
if (Platform.isIOS) {
showCupertinoDialog(
context: context,
builder: (context) {
return CupertinoAlertDialog(
title: Text("HI"),
content: Text("Are you there?"),
actions: [
CupertinoDialogAction(
child: Text("Yes"),
onPressed: () {},
),
CupertinoDialogAction(
child: Text("No"),
onPressed: () {},
)
],
);
},
);
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("HI"),
content: Text("Are you there?"),
actions: [
FlatButton(
child: Text("Yes"),
onPressed: () {},
),
FlatButton(
child: Text("No"),
onPressed: () {},
)
],
elevation: 24,
);
},
);
}
},
);
Check out this code, Hope it will help you
openDialog(bool showAlert, BuildContext context) async {
if(!showAlert) return;
var result = await showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text("HI"),
content: Text("Are you there?"),
actions: [
FlatButton(child: Text("Yes"), onPressed: () {
Navigator.pop(context, true);
},),
FlatButton(child: Text("No"), onPressed: () {
Navigator.pop(context, false);
},)
],
elevation: 24,
),
);
if(!(result ?? false)) {
// Yes click
} else {
// No click
}
}
Alternative
GetX Package Get.dialog()
And for many other scaffold components.
Dialog, Bottosheet, Snackbar, StateManagent Getx and Obx builder, and much more.
Visit pub.dev and search for GetX

AlertDialog not closing Flutter

my button code is as below and previously it closed the AlertDialog + Signed Out of Google when clicking on the continue button, but now it only signs out, the AlertDialog is still there... Anyone knows whats going on?
showAlertDialog(BuildContext context) {
// set up the buttons
Widget cancelButton = FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context, rootNavigator: true).pop();
},
);
Widget continueButton = FlatButton(
child: Text("Confirm Sign Out"),
onPressed: () {
signOutGoogle();
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) {
return LoginPage();
}), ModalRoute.withName('/'));
},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Confirmation"),
content: Text("Are you sure you want to Sign Out?"),
actions: [
cancelButton,
continueButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
showAlertDialog invoked here :
RaisedButton(
onPressed: () {
showAlertDialog(context);
},
color: Colors.deepPurple,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Sign Out',
style: TextStyle(fontSize: 25, color: Colors.white),
),
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40)),
)
Add Navigator.of(context).pop(); after signOutGoogle(); to close the dialog.
showAlertDialog(BuildContext context) {
// set up the buttons
Widget cancelButton = FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context, rootNavigator: true).pop();
},
);
Widget continueButton = FlatButton(
child: Text("Confirm Sign Out"),
onPressed: () {
signOutGoogle();
Navigator.of(context).pop(); // Pop the dialog
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) {
return LoginPage();
}), ModalRoute.withName('/'));
},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Confirmation"),
content: Text("Are you sure you want to Sign Out?"),
actions: [
cancelButton,
continueButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

How to disable onBackPressed() for AlertDialog flutter

I've got an AlertDialog() that it's barrierDismissible has been set to false. But yet when user presses the back button on android device the AlertDialog closes. How can I compeletly prevent the user from closing the AlertDialog()?
Here's what I've done so far:
return showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Title'),
content: Text('This is the alert dialog content'),
actions: <Widget>[
FlatButton(
child: Text('ok'),
onPressed: () {
Navigator.of(context).pop();
print('ok you win');
},
),
],
);
},
);
Try this way use WillPopScope() to handle onBackPressed() event
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () {return Future.value(false);},
child: return AlertDialog(
title: Text('Title'),
content: Text('This is the alert dialog content'),
actions: <Widget>[
FlatButton(
child: Text('ok'),
onPressed: () {
Navigator.of(context).pop();
print('ok you win');
},
),
],
),
);
});
You can use the WillPopScope as a parent of the AlertDialog
showDialog(context: context,builder: (BuildContext context)
{
return WillPopScope(
onWillPop: () async =>false,
child: AlertDialog(
title: Text('Title'),
content: Text('Sample'),
actions: <Widget>[
FlatButton(
child: Text('ok'),
onPressed: (){
Navigator.of(context).pop();
},
)
],
),
);