I have the following AlertDialog.
showDialog(
context: context,
child: new AlertDialog(
title: const Text("Location disabled"),
content: const Text(
"""
Location is disabled on this device. Please enable it and try again.
"""),
actions: [
new FlatButton(
child: const Text("Ok"),
onPressed: _dismissDialog,
),
],
),
);
How can I make _dismissDialog() dismiss said AlertDialog?
Navigator.pop() should do the trick. You can also use that to return the result of the dialog (if it presented the user with choices)
Navigator.of(context, rootNavigator: true).pop('dialog')
worked with me.
Navigator.pop(_)
worked for me, but the Flutter Team's gallery contains an example using:
Navigator.of(context, rootNavigator: true).pop()
which also works, and I am tempted to follow their lead.
If you don't want to return any result, use either of them:
Navigator.of(context).pop();
Navigator.pop(context);
But if you do want to return some result, see this
Example:
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text('Wanna Exit?'),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context, false), // passing false
child: Text('No'),
),
FlatButton(
onPressed: () => Navigator.pop(context, true), // passing true
child: Text('Yes'),
),
],
);
}).then((exit) {
if (exit == null) return;
if (exit) {
// user pressed Yes button
} else {
// user pressed No button
}
});
Generally Navigator.pop(context); works.
But If the application has multiple Navigator objects and dialogBox doesn't close, then try this
Navigator.of(context, rootNavigator: true).pop();
If you want to pass the result call, try
Navigator.pop(context,result);
OR
Navigator.of(context, rootNavigator: true).pop(result);
Navigator.of(dialogContext).pop() otherwise you can close page if you navigated from Master to Detail page
showDialog(
context: context,
builder: (dialogContext) {
return Dialog(
child: Column(
children: [
Text("Content"),
RaisedButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: Text("Close"),
)
],
),
);
},
);
Example of dismissing alert dialog on flat button click
RaisedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Are you sure?'),
content: Text('Do you want to remove item?'),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.of(context).pop(false),// We can return any object from here
child: Text('NO')),
FlatButton(
onPressed: () => Navigator.of(context).pop(true), // We can return any object from here
child: Text('YES'))
],
)).then((value) =>
print('Selected Alert Option: ' + value.toString()));
},
child: Text('Show Alert Dialog'),
),
Above code have two unique things which is used to provide callback result of dialog
Navigator.of(context).pop(false) -- return false value when we pressed
NO Navigator.of(context).pop(true) -- return true value when we
pressed YES
Based on these return value, we can perform some operation outside of it or maintain the dialog status value
This works Prefectly
RaisedButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
onPressed: () => Navigator.pop(context),
),
This worked for me Navigator.of(context, rootNavigator: true).pop('dialog').
Navigator.pop() just closes the current page/screen.
Creating a separate context for Alert Dialog would help.
showDialog(
context: context,
builder: (alertContext) => AlertDialog(
title: const Text("Location disabled"),
content: const Text(
"""Location is disabled on this device. Please enable it and try again."""),
actions: [
new FlatButton(
child: const Text("Ok"),
onPressed: () => Navigator.pop(alertContext),
),
],
),
);
Please use following for code to close dialog
RaisedButton(
onPressed: () { Navigator.of(context).pop();},
child: Text("Close",style: TextStyle(color: Colors.white), ),
color: Colors.black,
)
Use Navigator.pop(context);
Example
showDialog(
context: context,
child: new AlertDialog(
title: const Text("Location disabled"),
content: const Text(
"""
Location is disabled on this device. Please enable it and try again.
"""),
actions: [
new FlatButton(
child: const Text("Ok"),
onPressed: () {
Navigator.pop(context);
},
),
],
),
);
This answer works if you want to pop the dialog and navigate to another view. This part 'current_user_location' is the string the router need to know which view to navigate to.
FlatButton(
child: Text('NO'),
onPressed: () {
Navigator.popAndPushNamed(context, 'current_user_location');
},
),
This enough to dismisss dialog add inside Any callback like onpressed,ontap
Navigator.of(context).pop();
AlertDialog(
title: Center(child: Text("$title")),
insetPadding: EdgeInsets.zero,
titlePadding: EdgeInsets.only(top: 14.0, bottom: 4),
content: Container(
height: 50,
child: TextFormField(
controller: find_controller,
decoration: InputDecoration(
suffixIcon: context.watch<MediaProvider>().isChangeDialog
? IconButton(
onPressed: () {
clearController(find_controller);
},
icon: Icon(Icons.clear))
: null,
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurpleAccent)),
hintText: 'Id',
),
onChanged: (val) {
if (val.isNotEmpty)
context.read<MediaProvider>().isChangeDialog = true;
else
context.read<MediaProvider>().isChangeDialog = false;
},
),
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(4.0),
child: OutlinedButton(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Icon(Icons.clear),
),
),
Text("Cancel")
],
),
onPressed: () {
context.read<MediaProvider>().isChangeDialog = false;
//========================this enough to dismisss dialog
Navigator.of(context).pop();
}),
),
Padding(
padding: const EdgeInsets.all(4.0),
child: ElevatedButton(
onPressed: context.watch<MediaProvider>().isChangeDialog
? () {
context.read<MediaProvider>().isChangeDialog = false;
okCallback;
}
: null,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Icon(Icons.check),
),
),
Text("OK")
],
)),
)
],
),
],
);
pass it in the showDialog
barrierDismissible : true
use get package.
then Get.back() to close Modal
For Closing Dialog
void cancelClick() {
Navigator.pop(context);
}
The accepted answer states how to dismiss a dialog using the Navigator Class. To dismiss a dialog without using Navigator you can set the onPressed event of the button to the following:
setState((){
thisAlertDialog = null;
});
In case the code above is not self-explanatory it is basically setting the Parent AlertDialog of the FlatButton to null, thus dismissing it.
Related
I have a request to the server, when I use FutureBuilder, the ConnectionState.waiting section, I want to use a custom dialog, but after ConnectionState.done, this dialog does not close, it does not even do Navigator.pop(context).
enter image description here
enter image description here
Try this
Before ConnectionState.waiting just call this onLoading(context);
then
if(ConnectionState. done){
Navigator.pop();
}
void onLoading(BuildContext context) {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(color: Colors.blue));
});
}
Unfortunately, it is not possible to disable Alert Dialog using object orientation, and I designed dialogs on a separate page, and Navigator.pop() does not work, but with this method, I achieved my desired result.
FutureBuilder(
future: _futureEditName,
builder: (context,snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
ShowWaitingDialog(context,true);
}else if(snapshot.connectionState == ConnectionState.done && snapshot.hasData){
ShowWaitingDialog(context,false)
}
}
);
show and dismiss Alert Dialog
ShowWaitingDialog(BuildContext context,bool show) {
showDialog(
context: context,
builder: (context) {
return show == true ?
AlertDialog(
insetPadding: const EdgeInsets.all(20),
alignment: Alignment.center,
title: Container(
width: double.maxFinite,
child: Column(
textDirection: TextDirection.rtl,
children: [
Row(
textDirection: TextDirection.rtl,
children: [
const SpinKitCircle(
color: Colors.lightBlue,
size: 35,
),
const SizedBox(width: 20,),
Container(
alignment: Alignment.center,
child: const Text(
'please wait',
style: TextStyle(
color: kGraydark,
fontSize: 15,
),
),
),
],
),
],
),
),
)
: FutureBuilder(builder: (context, snapshot) {
Navigator.of(context).pop();
Navigator.of(context).pop();
return Container();
},);
},);
}
Navigator.of(context).pop() It must be called twice
Please help me!!!
I m new in flutter, i want to create like this in my flutter app on button click.
Try below code,
showModalBottomSheet(
context: context,
builder: (BuildContext cntx) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Icon(Icons.camera),
title: Text("Camera"),
onTap: () async {
},
),
ListTile(
leading: Icon(Icons.image),
title: Text("Files")),
onTap: () async {
},
),
Container(
height: 50,
color: prefix0.appBackgroundColcor,
child: ListTile(
title: Center(
child: Text(
"Cancel",
style: TextStyle(color: Colors.white),
),
),
onTap: () {
Navigator.pop(context);
},
),
)
],
);
});
You can use cupertino bottom modal to achieve something like that. See below code for implementation:
void show() {
showCupertinoModalPopup(
context: context,
builder: (BuildContext cont) {
return CupertinoActionSheet(
actions: [
CupertinoActionSheetAction(
onPressed: () {
print('Camera');
},
child: Text('Use Camera'),
),
CupertinoActionSheetAction(
onPressed: () {
print('Upload files');
},
child: Text('Upload from files'),
),
CupertinoActionSheetAction(
onPressed: () {
print('Dropbox');
},
child: Text('Upload from DropBox'),
)
],
cancelButton: CupertinoActionSheetAction(
onPressed: () {
Navigator.of(cont).pop;
},
child: Text('Cancel', style: TextStyle(color: Colors.red)),
),
);
});
}
Call the show function with the press of any button. You will see something like this.
If you don't want the divider between actions you have to create your own custom popup.
I am developing a flutter app that has a customer listing and a "Add" Floating button. When i click on Add button , I am taking it to a new screen for adding new customer. In this screen, when device back button is pressed, It should go back to the listing screen. But, instead it is going back to Dashboard.(App Flow : Dashboard screen(Customers) -> Customer Listing screen -> Add customer Screen.
I have already tried the Willscope method :
My Add Customer Screen:
Widget build(BuildContext context) {
Future<bool> _onBackPressed() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit Add Customer'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
)) ?? false;
}
return new
WillPopScope(
onWillPop: _onBackPressed,
child : new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
backgroundColor: theme_color,
),
body: new SafeArea(
top: false,
bottom: false,
child: new Form(
key: _formKey,
autovalidate: true,
child: new ListView(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
children: <Widget>[
SizedBox(
height: 20,
),
//Form Elements
new Container(
height: 70,
padding: const EdgeInsets.only(
left: 10.0, right: 10.0, top: 20.0),
child: new RaisedButton(
color: theme_color,
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
onPressed: () {
//Send Data to Database
}
},
)), //Save button
],
))),
));
}
Use this , Instead of return anything .
Future<void> _onBackPressed() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit Add Customer'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
));
}
How does one implement a menu widget on iOS equivalent to the Android (Material) drawer in Flutter?
There is no straightforward alternative menu widget in iOS, because Apple doesn't recommend drawers at all.
A drawer is a type of interface element that contains options or information
related to a specific window. A drawer is hidden by default, and can
only be revealed when the parent window is visible on screen. When
revealed, typically in response to a button, menu, or action, the
drawer slides out from one of side of the parent window. A drawer
can’t be moved separately or detached from its parent window.
Avoid using drawers. Drawers are seldom used in modern apps and their
use is discouraged. Panels, popovers, sidebars, and split views are
preferred for displaying supplementary window content.
Quick solution
Example
The Flutter team has prepared a comprehensive example of Android / iOS multiplatform app design.
You can build this yourself. You can use Positioned and GestureDetector, for example. Than you can animate it's moving. Is done very easy.
If you really want, you can workaround by defining a page that you use in the drawer for Android and as just another page for iOS:
Widget settingsWheel = Platform.isAndroid
? Builder(builder: (BuildContext context) => IconButton(
icon: settingsIcon,
onPressed: () => Scaffold.of(context).openDrawer(),
tooltip: "Open App Settings",
))
: Builder(builder: (BuildContext context) => CupertinoButton(
child: settingsIcon,
onPressed: () => Navigator.pushNamed(context, AppSettings.pageRoute),
));
...and then give it a "drawer-ish" feel by sliding the page in from the left:
onGenerateRoute: (route){
if (route.name == AppSettings.pageRoute) {
return PageTransition(
child: AppSettings(),
type: PageTransitionType.leftToRight,
settings: route,);
}
Simply place the Drawer in the endDrawer attribute of Scaffold, example:
Drawer(
child: ListView(shrinkWrap: true,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: BoxDecoration(
color: myColour,
),
accountName:
Padding(child: Row(
children: <Widget>[
Text("Marcelo Augusto Elias"),
IconButton(
icon: Icon(
Icons.edit,
color: whiteColour,
),
onPressed: () {},
),
],
), padding: EdgeInsets.only(top: 10),),
accountEmail: Text("N° Cartão: XXXX XXXX XXXX 5154"),
currentAccountPicture: CircleAvatar(
backgroundColor:
Theme.of(context).platform == TargetPlatform.iOS
? myColour
: Colors.white,
child: Icon(
Icons.person,
size: 50,
),
),
),
ListTile(
dense: true,
title: Text("Fatura"),
leading: new Image.asset(
"assets/images/icon_fatura_barra_menu.png",
width: 20.0,
),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Fatura()),
);
},
),
ListTile(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ConsultaMargem()),
);
},
dense: true,
title: Text("Extrato"),
leading: new Image.asset(
"assets/images/icon_barra_menu_extrato.png",
width: 20.0,
),
),
ListTile(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DesbloquearPrimeiraVia()),
);
},
dense: true,
title: Text("Desbloquear Cartão"),
leading: new Image.asset(
"assets/images/icon_barra_menu_desbloquearcartao.png",
width: 24.0,
),
),
ListTile(
dense: true,
title: Text("Meu Cartão"),
leading: new Image.asset(
"assets/images/icon_barra_menu_meucartao.png",
width: 20.0,
),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Contracheques()),
);
},
),
ListTile(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HistoricoConsignacoes()),
);
},
dense: true,
title: Text("Adiantamento Salarial"),
leading: new Image.asset(
"assets/images/icon_barra_menu_adiantamentosalarial.png",
width: 20.0,
),
),
/* ListTile(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ConsultaMargem()),
);
},
dense: true,
title: Text("Consulta de Margem"),
leading: new Image.asset(
"assets/images/icon_consulta_margem.png",
width: 20.0,
),
), */
/* ListTile(
dense: true,
title: Text("Informe de Rendimentos"),
leading: new Image.asset(
"assets/images/icon_rendimento.png",
width: 20.0,
),
), */
/* ListTile(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SimularEmprestimos()),
);
},
dense: true,
title: Text("Simular Empréstimo"),
leading: new Image.asset(
"assets/images/Icon_cal.png",
width: 20.0,
),
), */
Divider(),
ListTile(
dense: true,
title: Text("Compartilhar"),
leading: new Image.asset(
"assets/images/icon_compartilhar.png",
width: 20.0,
),
),
ListTile(
dense: true,
title: Text("Avaliar"),
leading: new Image.asset(
"assets/images/icon_estrela.png",
width: 20.0,
),
),
Divider(),
ListTile(
onTap: () {
Navigator.pop(context);
},
dense: true,
title: Text("Sair"),
trailing: Text(
"Versão 2.0",
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
),
leading: new Image.asset(
"assets/images/icon_porta_sair.png",
width: 20.0,
),
),
],
),
)
I have a strange problem with AlertDialog in flutter to dismiss the dialog. I was using the below code snippet to close the dialog as mentioned in the flutter documentation.
Navigator.of(dialogContext).pop();
But show how it doesn`t work and make the app into the inactive mode and turns into the black screen window. To make it work again, i have to kill the app and restart again.
Here is the complete code for alertdialog in flutter
Future<Null> _showDialogContactDial(context, Contact contactRecord) async {
return showDialog<Null>(
context: context,
barrierDismissible: true, // user must tap button!
builder: (BuildContext dialogContext) {
return new AlertDialog(
title: new Text('Confirm Number'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new TextFormField(
maxLines: 1,
decoration: new InputDecoration(hintText: 'Number'),
keyboardType: TextInputType.number,
autofocus: false,
initialValue: contactRecord.phoneNumber.number,
),
],
),
),
actions: <Widget>[
new FlatButton(
child: new Text(
'Call',
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(dialogContext).pop();
_launchURL(
context);
},
),
new FlatButton(
color: Colors.red,
child: new Text('Close', style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.of(dialogContext).pop();
},
),
],
);
},
);
}
I also noticed that it works for one button "call" without any issues but not for the cancel alert dialog as you see in the same code snippet in both button actions.
Help would be appreciated.
Just add rootNavigator:true
Navigator.of(dialogcon, rootNavigator: true).pop();
This worked in my application , i have made little changes in your code ,hope this might help , if this doesn't help you then I think here is a problem in _launchURl method.
void _showDialogContactDial(BuildContext context, Contact contactRecord){
showDialog<Null>(
context: context,
barrierDismissible: true, // user must tap button!
builder: (BuildContext dialogContext) {
return new AlertDialog(
title: new Text('Confirm Number'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new TextFormField(
maxLines: 1,
decoration: new InputDecoration(hintText: 'Number'),
keyboardType: TextInputType.number,
autofocus: false,
initialValue: contactRecord.phoneNumber.number,
),
],
),
),
actions: <Widget>[
new FlatButton(
child: new Text(
'Call',
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(dialogContext).pop();
_launchURL(
context);
},
),
new FlatButton(
color: Colors.red,
child: new Text('Close', style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.of(dialogContext).pop();
},
),
],
);
},
);
}
Use this method as a callback for onTap or wherever you are using it.
Inside your dialog. Surround your flatbuttons with Builder.
Builder(
builder: (context) => FlatButton(
child: Text('Cancelar'),
onPressed: () {
Navigator.of(context).pop();
},
),
),