Device Back button control in Flutter - android

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'),
),
],
),
));
}

Related

How can i navigate to several new pages using the bottom navigation bar in flutter?

I want to navigate to several new pages using my bottom navigation bar in flutter.
I tried several methods to achieve my requirement. But still neither of them worked out for me. I have attached my relevant entire source code below for a better understanding.
Thank you in advance. :)
Dart Source Code :
class dashboard extends StatefulWidget {
#override
_dashboardState createState() => _dashboardState();
}
// ignore: camel_case_types
class _dashboardState extends State<dashboard> {
#override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context);
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 80.0, right: 250),
child: Center(
child: Container(
width: 200.0,
height: 20.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(15.0)),
child: (const Text(
'Hello',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.black),
)),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: MaterialButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => profile()));
},
child: const Text('Test'),
),
),
Padding(
padding: EdgeInsets.only(left: 300.0, top: 10.0),
child: IconButton(
icon: new Icon(Icons.notifications),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Notifications(),
),
);
},
),
),
Padding(
padding: const EdgeInsets.only(top: 1.0),
child: Center(
child: Container(
width: 390,
height: 450,
decoration: BoxDecoration(
color: Colors.green.shade100,
borderRadius: BorderRadius.circular(10.0)),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: () async {
await authService.signOut();
}),
// : _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.book_online),
label: 'Page 1',
),
BottomNavigationBarItem(
icon: Icon(Icons.read_more),
label: 'Page 2',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: 'Page 3',
),
],
),
);
}
}
There are many propositions, this is one :
first, you begin by adding a variable index to know where you are. then add a function to change the content of this variable.
class _dashboardState extends State< dashboard > {
int currentIndex = 1;
changeIndex(index) {
setState(() {
currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: WillPopScope(
child: (currentIndex == 1)
? HomeScreen()
: (currentIndex == 2)
? Screen2()
: (currentIndex == 3)
? Screen3()
: Settings(),
onWillPop: () async {
bool backStatus = onWillPop();
if (backStatus) {
exit(0);
}
return false;
},
),
then link it to the navbar button.
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const [
InkWell(
onTap: () => changeIndex(1),
child: BottomNavigationBarItem(
icon: Icon(Icons.book_online),
label: 'Page 1',
),
.....
],
),

how to handle the back button of andriod in flutter

I am working on an flutter application where it has more than 5 screens, I want to handle the back button of android, for example, when I logged in on app, it display the dashboard screen, so when I move to profile and then move to history screen, and when I click on back button on history screen it should navigate to profile screen, because the last screen I visited before history screen is profile, but it display the first screen which login screen.
I found the solution which works like when I click on back button it close the app.
Update:
My screens are navigating from drawer and from bottom navigation, there is only login screen where i use login button and calling dashboard screen onpressed function, other than this there is no button on any screen which navigate to other screens. here is the code for drawer and bottom navigation.
this is line of code i am using on login button
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Employee()));
drawer and bottom navigation code:
Code:
class Employee extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
theme: new ThemeData(
primaryColor: Colors.blue
),
home: EmployeeNavigation(),
);
}
}
int _selectedTab = 0;
final _pageOptions = [
EmployeeDashboard(),
location(),
Profile()
];
String getname="";
String getemail="";
String getdesignation="";
String getaccesstoken="";
String getdate;
String getTime;
// ignore: must_be_immutable
class EmployeeNavigation extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return EmployeeNavigationState();
}
}
class EmployeeNavigationState extends State<EmployeeNavigation> {
var email;
var designation;
var date;
bool valuefirst = false;
String backtext="";
#override
Widget build(BuildContext context) {
//i used this too but it doesn't work.
return WillPopScope(
onWillPop: () async {
if (_selectedTab == 0) {
return true;
}
setState(() {
_selectedTab = 0;
});
return false;
},
child:Scaffold(
drawer:Emp_DrawerCode(),
body: _pageOptions[_selectedTab],
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue[50],
type: BottomNavigationBarType.fixed,
currentIndex: _selectedTab,
onTap: (value) {
print(value);
setState(() {
_selectedTab = value;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
BottomNavigationBarItem(icon: Icon(Icons.location_on), label: "Location"),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: "Profile",
),
],
)));
}
}
class Emp_DrawerCode extends StatefulWidget {
#override
_Emp_DrawerCodeState createState() => _Emp_DrawerCodeState();
}
class _Emp_DrawerCodeState extends State<Emp_DrawerCode> {
SharedPreferences myPrefs;
name() async{
myPrefs=await SharedPreferences.getInstance();
setState(() {
getname=myPrefs.getString('name');
getemail=myPrefs.getString('email');
getdesignation=myPrefs.getString('designation');
});
}
void initState(){
name();
}
#override
Widget build(BuildContext context) {
return new Drawer(
child: new ListView(
padding: const EdgeInsets.all(0.0),
children: <Widget>[
new UserAccountsDrawerHeader(
accountName: new Text(getname),
accountEmail: new Text(getemail),
currentAccountPicture: new CircleAvatar(
backgroundColor:
Theme.of(context).platform == TargetPlatform.android
? Colors.white
: Colors.blue,
child: Text(
getname[0][0],
style: TextStyle(fontSize: 40.0),
),
),
),
new ListTile(
title: new Text('Home'),
leading: Icon(Icons.dashboard,color:Colors.grey),
onTap: (){
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=> EmployeeNavigation()
)
);
},
),
new ListTile(
title: new Text('Request for leave'),
leading: Icon(Icons.request_page,color:Colors.grey),
onTap: (){
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=>RequestForLeave()
)
);
},
),
new ExpansionTile(
title: new Text('History'),
children: <Widget>[
ListTile(
title:new Text("My Attendance"),
leading: Icon(Icons.assessment_outlined ,color:Colors.grey),
onTap: (){
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=>new MyAttendance()
)
);
},
),
ListTile(
title:new Text("Leaves"),
leading: Icon(Icons.assessment_outlined,color:Colors.grey ),
onTap: (){
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=>new LeaveHistory()
)
);
},
),
],
leading: Icon(Icons.history,),
),
new ListTile(
title: new Text('Log out'),
leading: Icon(Icons.logout,color:Colors.grey),
onTap: (){
myPrefs.setBool('login', true);
Navigator.pop(context);
Navigator.push(context, new MaterialPageRoute(
builder: (context)=>
Login()
)
);
},
),
],
),
);
}
}
kindly please help how to do this.
I am using navigator.push method and it is acting as you want.
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.blue),
onPressed: () => Navigator.of(context).pop(),
),
title: Text("Sample"),
centerTitle: true,
),
I wish it solve your problem.
You need to first clarify your question a bit more.
Are using page view/ are you talking about a scenario where all are separately navigable screens or some different scenario ?
I am considering it as the second scenario when all are separately navigable screens.
In that case, every time user navigates to next screen you must use Navigator.pushNamed() / Navigator.push() as for now I think you are using Navigator.pushReplacement() which is causing this issue probably.
Navigator is nothing but a class aware of the stack of screens in the memory and so are the functions it provides us with. A simple push would mean pushing over the last pushed screen whereas pushing a replacement would replace the last pushed screen ultimately preventing you from navigating to the last pushed screen. Exactly like how it would work for a stack data structure.
Firstly Wrap your Scaffold with WillPopScope
return WillPopScope(
onWillPop: _onBackPressed,
child : Scaffold());
And then you can call the Function that handles the back press.
// Back Button Android Behaviour
Future<bool> _onBackPressed() async {
final shouldPop = await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Are you sure you want to leave this page?",
style: TextStyle(
color: Colors.black,
fontSize: 25.0,
fontWeight: FontWeight.w500,
),
),
actions: <Widget>[
SizedBox(width: 16),
InkWell(
onTap: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => HomeScreen(), // Destination
),
(route) => false,
);
},
child: Container(
padding: EdgeInsets.all(8.0),
child: Text(
"LEAVE",
style: TextStyle(
color: Colors.red,
fontSize: 20.0,
fontWeight: FontWeight.w500,
),
),
),
),
SizedBox(width: 8.0),
InkWell(
onTap: () => Navigator.of(context).pop(false),
child: Container(
padding: EdgeInsets.all(8.0),
child: Text(
"DO NOT LEAVE",
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
fontWeight: FontWeight.w500,
),
),
),
),
],
));
return shouldPop ?? false;
}

Flutter multi-platform Android / iOS drawer menu

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,
),
),
],
),
)

Navigate using bottom app bar tabs - flutter

I am using bottom app bar for bottomnavigation in flutter. when tapped on one of the tab in the bottom app bar, i would still want the bottom app bar and app bar to remain as it is in it's fixed position but only the body content changes based on what is tapped.
I have tried to use push() method but it gives me a new page instead with a back button.
Navigation_tabs.dart:
import 'package:flutter/material.dart';
class NavigationTabs extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {},
),
appBar: AppBar(
title: Text('Dashboard'),
),
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
notchMargin: 4.0,
child: new Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.home,
color: Colors.cyan[700],
),
onPressed: () {},
),
new Container(
padding: EdgeInsets.only(left: 20),
child: IconButton(
icon: Icon(
Icons.list,
color: Colors.cyan[700],
),
onPressed: () => Navigator.pushNamed(context, '/login'),
)),
new Container(
padding: EdgeInsets.only(left: 120),
child: IconButton(
icon: Icon(
Icons.explore,
color: Colors.cyan[700],
),
onPressed: () {},
)),
new Container(
height: 22.0,
child: new RawMaterialButton(
onPressed: () {},
child: new Icon(
Icons.person,
color: Colors.white,
size: 20.0,
),
shape: new CircleBorder(),
elevation: 1.0,
fillColor: Colors.cyan[700],
))
],
),
));
}
}
I want to be able to only make the page content change without a back button instead of going to a completely new page when one of the tabs is pressed.
You can use a BottomNavigationBarItem instead of creating buttons and use the ontap of the bottomNavigationBar.
class _MyHomePageState extends State<MyHomePage> {
int _index = 0;
final List<Widget> _children = [
Center(child: Text("First Page"),),
Center(child: Text("Second Page"),),
Center(child: Text("Third Page"),)
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bottom Navigation"),
),
body: Center(
child: (_children[_index ]),
),
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.looks_one),
title: Text('First'),
),
BottomNavigationBarItem(
icon: Icon(Icons.looks_two),
title: Text('Second'),
),
BottomNavigationBarItem(
icon: Icon(Icons.looks_3),
title: Text('Third'),
)
],
),
);
}
void onTabTapped(int index) {
setState(() {
_index = index;
});
}
}
For more detailed explanation:
Flutter documentation

How to dismiss an AlertDialog on a FlatButton click?

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.

Categories

Resources