How to add a AlertDialog in ListTile - dart

I want to show a AlertDialog whenever I Tap on the ListTile. I want to add the AlertDialog in the OnTap functon in the ListTile as shown in the code.
import "package:flutter/material.dart";
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Exploring Ui Widgets',
home: Scaffold(
body: getListView(),
),
));
}
Widget getListView() {
var listview = ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.accessible),
title: Text('Get Up!'),
subtitle: Text('Use your Legs!'),
trailing: Icon(Icons.accessible_forward),
onTap: () {
// I want to add a AlertDialog here!
},
),
ListTile(
leading: Icon(Icons.airline_seat_individual_suite),
title: Text('Wake Up!'),
subtitle: Text('Dont Sleep!'),
trailing: Icon(Icons.airline_seat_flat_angled),
)
],
);
return listview;
}

You can do it like this:
onTap: () => alertDialog(context),
Then declare this method:
void alertDialog(BuildContext context) {
var alert = AlertDialog(
title: Text("My title"),
content: Text("Dialog description"),
);
showDialog(context: context, builder: (BuildContext context) => alert);
}
It would look like this inside your code:
import "package:flutter/material.dart";
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Exploring Ui Widgets',
home: Scaffold(
body: getListView(),
),
));
}
Widget getListView() {
var listview = ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.accessible),
title: Text('Get Up!'),
subtitle: Text('Use your Legs!'),
trailing: Icon(Icons.accessible_forward),
onTap: () {
onTap: () => alertDialog(context),
},
),
ListTile(
leading: Icon(Icons.airline_seat_individual_suite),
title: Text('Wake Up!'),
subtitle: Text('Dont Sleep!'),
trailing: Icon(Icons.airline_seat_flat_angled),
)
],
);
return listview;
}
void alertDialog(BuildContext context) {
var alert = AlertDialog(
title: Text("Dialog title"),
content: Text("Dialog description"),
);
showDialog(context: context, builder: (BuildContext context) => alert);
}

Related

how to handle notifications flutter

I'm using firebase to send notifications to my app what happens is that I reserved the notifications in the terminal but it's not shown in my application
so how can I handle the notification in a widget so it appears inside the application
I'm trying to set state the text message variable so that its value become the notification body instead of null but its not working
my code is that
[import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:idb/pages/aboutus.dart';
import 'package:idb/pages/adminpage.dart';
import 'package:idb/pages/changePassword.dart';
import 'package:idb/pages/homepage.dart';
import 'package:idb/pages/logout.dart';
import 'package:idb/pages/newsPage.dart';
import 'dart:io';
class NotificationsPage extends StatefulWidget {
_NotificationsPageState createState() => _NotificationsPageState();
}
class _NotificationsPageState extends State<NotificationsPage> {
final FirebaseMessaging _messaging = new FirebaseMessaging();
//String testMessage;
Map<String, dynamic> testMessage;
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_messaging.getToken().then((token) {
print('notification token $token');
});
_messaging.configure(
onMessage: (Map<String, dynamic> message) async {
// print('message ${message}');
setState(() {
testMessage = message\['notification'\]\['body'\];
print('testMessage ${testMessage}');
});
},
onResume: (Map<String, dynamic> message) async {
// print('message ${message}');
//print('on resume ${message\['notification'\]\['body'\]}');
setState(() {
String testMessage = message\['notification'\]\['body'\];
print('testMessage onResume ${testMessage}');
});
},
onLaunch: (Map<String, dynamic> message) async {
// print('message ${message}');
// print('on launch $message');
setState(() {
String testMessage = message\['notification'\]\['body'\];
print('testMessage onLaunch ${testMessage}');
});
},
);
}
void iOS_Permission() {
_messaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_messaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
int _cIndex = 1;
void _incrementTab(index) {
setState(() {
_cIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: new Drawer(
child: new ListView(children: <Widget>\[
new Container(
child: new DrawerHeader(
child: Image.asset('assets/t.jpg'),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => AdminPage()),
);
},
),
ListTile(
leading: Icon(Icons.credit_card),
title: Text('My Cards'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => HomePage()),
);
},
),
ListTile(
leading: Icon(Icons.message),
title: Text('News'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => NewsPage()),
);
},
),
ListTile(
leading: Icon(Icons.info),
title: Text('About Us'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => AboutUs()),
);
},
),
Divider(),
ListTile(
leading: Icon(Icons.lock_outline),
title: Text('Change Password'),
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => ChangePassword()),
);
},
),
Logout(),
\]),
),
appBar: AppBar(
title: Text(
'Notifications',
style: TextStyle(color: Colors.blueGrey),
),
backgroundColor: Colors.grey\[100\],
centerTitle: true,
elevation: 0.0,
),
body: Center(
child: Container(
child: Text(
'$testMessage',
style:
new TextStyle(color: Colors.grey, fontWeight: FontWeight.w400),
),
),
),
bottomNavigationBar: BottomNavigationBar(
fixedColor: Colors.orange,
currentIndex: _cIndex,
//fixedColor: Colors.grey\[100\],
type: BottomNavigationBarType.shifting,
items: \[
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: Colors.blueGrey,
),
title: Text('Home',
style: TextStyle(
color: Colors.blueGrey,
)),
),
BottomNavigationBarItem(
icon: Icon(
Icons.notifications,
color: Colors.blueGrey,
),
title: Text('Notifications',
style: TextStyle(
color: Colors.blueGrey,
)),
),
BottomNavigationBarItem(
icon: Icon(
Icons.message,
color: Colors.blueGrey,
),
title: Text('News',
style: TextStyle(
color: Colors.blueGrey,
)),
),
\],
onTap: (index) {
if (index == 0) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => AdminPage()),
);
}
if (index == 1) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => NotificationsPage()),
);
}
if (index == 2) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => NewsPage()),
);
}
_incrementTab(index);
// _incrementTab(index);
},
),
);
}
#override
void initState() {
super.initState();
firebaseCloudMessaging_Listeners();
}
}
]1]1

ListWheelScrollView children do not recognize onTap()

The children of a ListWheelScrollView do not recognize taps. How can I make the children of a ListWheelScrollView recognize taps? I think there is some kind of scrollable widget infront of the children which is preventing the children from being clicked. If I put this code inside of a listview, everything works fine, but not for a listWheelScrollView
Here's my code
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
'List Wheel',
),
),
body: myListWheel,
),
),
);
}
Widget myListWheel = ListWheelScrollView (
itemExtent: 100,
children: <Widget>[
ListTile(
enabled: true,
onTap: () {
print('Hello, World');
},
title: Text(
'First',
),
subtitle: Text(
'this is subtitle'
),
),
ListTile(
enabled: true,
onTap: () {
print('Hello, World');
},
title: Text(
'Second',
),
subtitle: Text(
'this is a subtitle'
),
),
],
);
Last month, Michael Lang (Cilestal) published a new clickable_list_wheel_widget package.
Behavior:
When you click on the selected item, onItemTapCallback is called on the ClickableListWheelScrollView
When you click on another item, onItemTapCallback is called on the ClickableListWheelScrollView, immediately followed by a call to onSelectedItemChanged on the ListWheelScrollView
import 'package:flutter/material.dart';
import 'package:clickable_list_wheel_view/clickable_list_wheel_widget.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
'List Wheel',
),
),
body: MyListWheel(),
),
),
);
}
class MyListWheel extends StatelessWidget {
final _scrollController = FixedExtentScrollController();
final double _itemHeight = 100.0;
final data = List.generate(20, (index) => 'Item $index');
#override
Widget build(BuildContext context) {
return ClickableListWheelScrollView(
scrollController: _scrollController,
itemHeight: _itemHeight,
itemCount: data.length,
onItemTapCallback: (index) {
print("onItemTapCallback index: $index");
},
child: ListWheelScrollView.useDelegate(
controller: _scrollController,
itemExtent: _itemHeight,
physics: FixedExtentScrollPhysics(),
overAndUnderCenterOpacity: 0.5,
perspective: 0.002,
onSelectedItemChanged: (index) {
print("onSelectedItemChanged index: $index");
},
childDelegate: ListWheelChildBuilderDelegate(
builder: (context, index) => ListTile(title: Text(data[index])),
childCount: data.length,
),
),
);
}
}

How to use conditional statement within onTap

I have a problem regarding if statement in dart, I want the user to tap the city to go to a new screen. this code work perfectly fine
class citySec extends StatelessWidget {
Widget getListView(BuildContext context) {
var listView = ListView(
children: <Widget>[
Text(
"choose ur city:",
textDirection: TextDirection.rtl,
textAlign: TextAlign.center,
),
ListTile(
leading: Icon(Icons.location_city),
title: Text("Toronto ", textDirection: TextDirection.rtl),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TorontoUniversitySection(),
),
);
},
),
],
);
return listView;
}
#override
Widget build(BuildContext context) {
return Scaffold(body: getListView(context));
}
}
Since I have a long list of cities and the previous code will make my code very long so I had to change my code. However, I faced some errors with if statements, here is what I did so far.
import 'package:flutter/material.dart';
import 'package:rate/screens/firstScreen.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Rate',
home: Scaffold(
appBar: AppBar(
title: Text("jgfnjfnj ", textDirection: TextDirection.rtl),
),
body: ListDisplay(),
),
));
}
class ListDisplay extends StatelessWidget {
List<String> litems = ["Toronto","NewYork","London","Riyadh","Dubai","Istanbul"];
#override
Widget build (BuildContext ctxt) {
return new Scaffold(
appBar: AppBar(title: Text("Please Choose your city: ", textDirection: TextDirection.ltr,),
),
body: new ListView.builder
(
itemCount: litems.length,
itemBuilder: (BuildContext ctxt, int index) {
return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),
onTap: () {
// begin of all IF statements
if (litems.contains("Totonto")){
Navigator.push(
ctxt,
MaterialPageRoute(
builder: (ctxt) => TorontoUniversitySection()
),
);
}
if (litems.contains("London")){
Navigator.push(
ctxt,
MaterialPageRoute(
builder: (ctxt) => LondonUniversitySection()
),
);
}
// end of all If statements
},
);
}
)
);
}
}
for example, when I press Toronto it will take me to LondonUniversitySection()
That is because in your if statements, you check whether your list contains Toronto/London and not if currently pressed one is Toronto/London. Changing litems.contains("x") to litems[index] == "x" will do the trick. Here's edited fragment:
return new ListTile(
leading: Icon(Icons.location_city),
title: Text(litems[index], textDirection: TextDirection.rtl),
onTap: () {
if (litems[index] == "Toronto") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => TorontoUniversitySection()),
);
} else if (litems[index] == "London") {
Navigator.push(
ctxt,
MaterialPageRoute(builder: (ctxt) => LondonUniversitySection()));
}
},
);
Also, I recommend using a switch or else-if for that, not a bunch of ifs.
Try onTap: litems.contains("Totonto")?
Navigator.push( ctxt, MaterialPageRoute( builder: (ctxt) => TorontoUniversitySection() ), )
: null
class _RegisterBodyState extends State<RegisterBody> {
FocusNode myFocusNode = new FocusNode();
FocusNode myFocusNode2 = new FocusNode();
void initState() {
super.initState();
myFocusNode = FocusNode();
myFocusNode2 = FocusNode();
}
#override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
myFocusNode2.dispose();
super.dispose();
}
Color color;
#override
Widget build(BuildContext context) {
return Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Register",
style: TextStyle(
color: Theme.of(context).primaryColor,
fontSize: 70.0,
fontWeight: FontWeight.bold,
),
),
Form(
child: Column(
children: [
TextFormField(
onTap: () {
setState(() {
color = Colors.red;
});
},
autofocus: true,
focusNode: myFocusNode,
decoration: InputDecoration(
icon: Icon(
Icons.supervised_user_circle,
size: 40.0,
),
labelText: "User Name",
labelStyle: TextStyle(
color:
myFocusNode.hasFocus ?color : Colors.yellow),
),
),
TextFormField(
focusNode: myFocusNode2,
onTap: () {
setState(() {
color = Colors.black;
});
},
autofocus: false,
decoration: InputDecoration(
icon: Icon(
Icons.supervised_user_circle,
size: 40.0,
),
labelText: "User Name",
labelStyle: TextStyle(
color: myFocusNode2.hasFocus ? color : Colors.teal,
),
),
),
],
))
],
),
),
);
}
}

How to make an AlertDialog in Flutter?

I am learning to build apps in Flutter. Now I have come to alert dialogs. I have done them before in Android and iOS, but how do I make an alert in Flutter?
Here are some related SO questions:
How to style AlertDialog Actions in Flutter
adding dropdown menu in alert dialog box in flutter
Show alert dialog on app main screen load automatically
how to refresh alertdialog in flutter
Alert Dialog with Rounded corners in flutter
I'd like to make a more general canonical Q&A so my answer is below.
One Button
showAlertDialog(BuildContext context) {
// set up the button
Widget okButton = TextButton(
child: Text("OK"),
onPressed: () { },
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("My title"),
content: Text("This is my message."),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Two Buttons
showAlertDialog(BuildContext context) {
// set up the buttons
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed: () {},
);
Widget continueButton = TextButton(
child: Text("Continue"),
onPressed: () {},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("AlertDialog"),
content: Text("Would you like to continue learning how to use Flutter alerts?"),
actions: [
cancelButton,
continueButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Three Buttons
showAlertDialog(BuildContext context) {
// set up the buttons
Widget remindButton = TextButton(
child: Text("Remind me later"),
onPressed: () {},
);
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed: () {},
);
Widget launchButton = TextButton(
child: Text("Launch missile"),
onPressed: () {},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Notice"),
content: Text("Launching this missile will destroy the entire universe. Is this what you intended to do?"),
actions: [
remindButton,
cancelButton,
launchButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Handling button presses
The onPressed callback for the buttons in the examples above were empty, but you could add something like this:
Widget launchButton = TextButton(
child: Text("Launch missile"),
onPressed: () {
Navigator.of(context).pop(); // dismiss dialog
launchMissile();
},
);
If you make the callback null, then the button will be disabled.
onPressed: null,
Supplemental code
Here is the code for main.dart in case you weren't getting the functions above to run.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: MyLayout()),
);
}
}
class MyLayout extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
child: Text('Show alert'),
onPressed: () {
showAlertDialog(context);
},
),
);
}
}
// replace this function with the examples above
showAlertDialog(BuildContext context) { ... }
I used similar approach, but I wanted to
Keep the Dialog code as a widget in a separated file so I can reuse it.
Blurr the background when the dialog is shown.
Code:
1. alertDialog_widget.dart
import 'dart:ui';
import 'package:flutter/material.dart';
class BlurryDialog extends StatelessWidget {
String title;
String content;
VoidCallback continueCallBack;
BlurryDialog(this.title, this.content, this.continueCallBack);
TextStyle textStyle = TextStyle (color: Colors.black);
#override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: AlertDialog(
title: new Text(title,style: textStyle,),
content: new Text(content, style: textStyle,),
actions: <Widget>[
new FlatButton(
child: new Text("Continue"),
onPressed: () {
continueCallBack();
},
),
new FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
));
}
}
You can call this in main (or wherever you want) by creating a new method like:
_showDialog(BuildContext context)
{
VoidCallback continueCallBack = () => {
Navigator.of(context).pop(),
// code on continue comes here
};
BlurryDialog alert = BlurryDialog("Abort","Are you sure you want to abort this operation?",continueCallBack);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
You can use this code snippet for creating a two buttoned Alert box,
import 'package:flutter/material.dart';
class BaseAlertDialog extends StatelessWidget {
//When creating please recheck 'context' if there is an error!
Color _color = Color.fromARGB(220, 117, 218 ,255);
String _title;
String _content;
String _yes;
String _no;
Function _yesOnPressed;
Function _noOnPressed;
BaseAlertDialog({String title, String content, Function yesOnPressed, Function noOnPressed, String yes = "Yes", String no = "No"}){
this._title = title;
this._content = content;
this._yesOnPressed = yesOnPressed;
this._noOnPressed = noOnPressed;
this._yes = yes;
this._no = no;
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: new Text(this._title),
content: new Text(this._content),
backgroundColor: this._color,
shape:
RoundedRectangleBorder(borderRadius: new BorderRadius.circular(15)),
actions: <Widget>[
new FlatButton(
child: new Text(this._yes),
textColor: Colors.greenAccent,
onPressed: () {
this._yesOnPressed();
},
),
new FlatButton(
child: Text(this._no),
textColor: Colors.redAccent,
onPressed: () {
this._noOnPressed();
},
),
],
);
}
}
To show the dialog you can have a method that calls it NB after importing BaseAlertDialog class
_confirmRegister() {
var baseDialog = BaseAlertDialog(
title: "Confirm Registration",
content: "I Agree that the information provided is correct",
yesOnPressed: () {},
noOnPressed: () {},
yes: "Agree",
no: "Cancel");
showDialog(context: context, builder: (BuildContext context) => baseDialog);
}
OUTPUT WILL BE LIKE THIS
Here is a shorter, but complete code.
If you need a dialog with only one button:
await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Message'),
content: Text(
'Your file is saved.'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(); // dismisses only the dialog and returns nothing
},
child: new Text('OK'),
),
],
),
);
If you need a dialog with Yes/No buttons:
onPressed: () async {
bool result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Confirmation'),
content: Text('Do you want to save?'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(false); // dismisses only the dialog and returns false
},
child: Text('No'),
),
FlatButton(
onPressed: () {
Navigator.of(context, rootNavigator: true)
.pop(true); // dismisses only the dialog and returns true
},
child: Text('Yes'),
),
],
);
},
);
if (result) {
if (missingvalue) {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text('Missing Value'),
));
} else {
saveObject();
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
} else {
Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}
Simply used this custom dialog class which field you not needed to leave it or make it null so this customization you got easily.
import 'package:flutter/material.dart';
class CustomAlertDialog extends StatelessWidget {
final Color bgColor;
final String title;
final String message;
final String positiveBtnText;
final String negativeBtnText;
final Function onPostivePressed;
final Function onNegativePressed;
final double circularBorderRadius;
CustomAlertDialog({
this.title,
this.message,
this.circularBorderRadius = 15.0,
this.bgColor = Colors.white,
this.positiveBtnText,
this.negativeBtnText,
this.onPostivePressed,
this.onNegativePressed,
}) : assert(bgColor != null),
assert(circularBorderRadius != null);
#override
Widget build(BuildContext context) {
return AlertDialog(
title: title != null ? Text(title) : null,
content: message != null ? Text(message) : null,
backgroundColor: bgColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(circularBorderRadius)),
actions: <Widget>[
negativeBtnText != null
? FlatButton(
child: Text(negativeBtnText),
textColor: Theme.of(context).accentColor,
onPressed: () {
Navigator.of(context).pop();
if (onNegativePressed != null) {
onNegativePressed();
}
},
)
: null,
positiveBtnText != null
? FlatButton(
child: Text(positiveBtnText),
textColor: Theme.of(context).accentColor,
onPressed: () {
if (onPostivePressed != null) {
onPostivePressed();
}
},
)
: null,
],
);
}
}
Usage:
var dialog = CustomAlertDialog(
title: "Logout",
message: "Are you sure, do you want to logout?",
onPostivePressed: () {},
positiveBtnText: 'Yes',
negativeBtnText: 'No');
showDialog(
context: context,
builder: (BuildContext context) => dialog);
Output:
Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.
Basic Alert:
Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();
Alert with Button:
Alert(
context: context,
type: AlertType.error,
title: "RFLUTTER ALERT",
desc: "Flutter is more awesome with RFlutter Alert.",
buttons: [
DialogButton(
child: Text(
"COOL",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
width: 120,
)
],
).show();
You can also define generic alert styles.
*I'm one of developer of RFlutter Alert.
Minumum code for alert dialog
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Title'),
content: Text(
'Content widget',
),
),
);
If you want beautiful and responsive alert dialog then you can use flutter packages like
rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert
These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.
showAlertDialog(BuildContext context, String message, String heading,
String buttonAcceptTitle, String buttonCancelTitle) {
// set up the buttons
Widget cancelButton = FlatButton(
child: Text(buttonCancelTitle),
onPressed: () {},
);
Widget continueButton = FlatButton(
child: Text(buttonAcceptTitle),
onPressed: () {
},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text(heading),
content: Text(message),
actions: [
cancelButton,
continueButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
called like:
showAlertDialog(context, 'Are you sure you want to delete?', "AppName" , "Ok", "Cancel");
Check out Flutter Dropdown Banner to easily alert users of events and prompt action without having to manage the complexity of presenting, delaying, and dismissing the component.
To set it up:
import 'packages:dropdown_banner/dropdown_banner.dart';
...
class MainApp extends StatelessWidget {
...
#override
Widget build(BuildContext context) {
final navigatorKey = GlobalKey<NavigatorState>();
...
return MaterialApp(
...
home: DropdownBanner(
child: Scaffold(...),
navigatorKey: navigatorKey,
),
);
}
}
To use it:
import 'packages:dropdown_banner/dropdown_banner.dart';
...
class SomeClass {
...
void doSomethingThenFail() {
DropdownBanner.showBanner(
text: 'Failed to complete network request',
color: Colors.red,
textStyle: TextStyle(color: Colors.white),
);
}
}
Click here to see an example
Just to add to the great answers - the best package I found is:
adaptive_dialog: ^1.8.0+1
For a one OK button the best thing I found is using showOkAlertDialog
Implementation:
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
Widget build(BuildContext context) {
return Container(
child: Center(
child: IconButton(
icon: Icon(
Icons.info,
),
onPressed: () => showOkAlertDialog(
context: context,
okLabel: 'OK',
title: 'Title',
message: 'This is the message',
),
)),
);
}
Clean and dismisses when you click 'Ok'.
If you need a dialog so this code for you. just use showDialog() onPress or any inside a function.
void showDialog() {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Login Failed!"),
content: const Text(
"Invalid credential !! Please check your email or password",
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: Container(
child: const Text(
"Try again",
style: TextStyle(color: Colors.cyan, fontSize: 17),
),
),
),
],
),
)}
Demo dialog screenshots
hope its helpful๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š
Simple and working solution that I used: Enjoy
// Sample can be used for exit dialog box on apps
showAlertDialog(BuildContext context) {
Widget okButton = TextButton(
child: const Text("Leave now",style: TextStyle(color: Colors.red),),
onPressed: () { SystemNavigator.pop(); },
);
Widget nopeButton = TextButton(
child: const Text("Stay here"),
onPressed: () { Navigator.pop(context); },
);
AlertDialog alert = AlertDialog(
title: const Text("Leave"),
content: const Text("Are you sure you want to leave?"),
actions: [
nopeButton,
okButton,
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Another easy option to show Dialog is to use stacked_services package
_dialogService.showDialog(
title: "Title",
description: "Dialog message Tex",
);
});
This code works and demonstrates how to obtain the button value pressed by the user:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatelessWidget(),
),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
// set up the buttons
Widget cancelButton = TextButton(
child: Text("Cancel"),
onPressed: () => Navigator.pop(context, 'Cancel'),
);
Widget continueButton = TextButton(
child: Text("Ok"),
onPressed: () => Navigator.pop(context, 'Ok'),
);
showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('AlertDialog Title'),
content: const Text('AlertDialog description'),
actions: <Widget>[
cancelButton,
continueButton,
],
),
).then((value) => print(value));
},
child: const Text('Show Dialog'),
);
}
}
Pressing on Ok button. then on Cancel button print
`showDialog<String>(
context: context,
builder: (BuildContext context) =>
AlertDialog(
title: const Text(
'Invalid Password',
style: TextStyle(color: Colors.red),
),
content:
const Text('Create Strong Password'),
actions: <Widget>[
Center(
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors
.red, // Background Color
),
onPressed: () => Navigator.pop(
context, 'Cancel'),
child: const Text('Cancel'),
),
),
],
),
),`

Bottom Navigation with Flutter

I try to build a App with flutter and have a problem by building the navigation. I want to have a navigation like in the current version of youtube app. A Bottom Navigation Bar with three Pages and than for each Page sub Pages with an owen navigation stack. On all subpages it shoud be possible to change the main view and the app shoud save on witch subpage i where. Is that possible? I found no solution for that. I think it shoud be possible because its on the example page of material Design: https://material.io/design/components/bottom-navigation.html#behavior at the Point "Bottom navigation actions".
I would be so thankful for help!
I'd take a look at this code snippet for help.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_nit2018/navigarion_drawer.dart';
import 'package:my_nit2018/pages/app/blog/blog_page.dart';
import 'package:my_nit2018/pages/app/home/home_page.dart';
import 'package:my_nit2018/pages/app/library/library_page.dart';
import 'package:my_nit2018/pages/app/notifications/notifications_page.dart';
class MainApp extends StatefulWidget {
FirebaseUser user;
MainApp(this.user);
#override
_MainAppState createState() => new _MainAppState();
}
class _MainAppState extends State<MainApp> {
int i = 0;
var pages = [
new HomePage(),
new BlogPage(),
new LibraryPage(),
new NotificationsPage()
];
#override
Widget build(BuildContext context) {
return new Scaffold(
body: pages[i],
drawer: new AppNavigationDrawer(),
bottomNavigationBar: new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.photo_library),
title: new Text('Blog'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.book),
title: new Text('Library'),
),
new BottomNavigationBarItem(
icon: new Icon(Icons.notifications),
title: new Text('Notifications'),
),
],
currentIndex: i,
type: BottomNavigationBarType.fixed,
onTap: (index) {
setState(() {
i = index;
});
},
),
);
}
}
AppNavigationDrawer:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_nit2018/pages/app/app_state.dart';
import 'package:my_nit2018/pages/app/main_app.dart';
import 'package:my_nit2018/pages/app/profile/profile_page.dart';
import 'package:my_nit2018/pages/auth/login_page.dart';
class AppNavigationDrawer extends StatefulWidget {
#override
_AppNavigationDrawerState createState() => new
_AppNavigationDrawerState();
}
class _AppNavigationDrawerState extends State<AppNavigationDrawer> {
#override
Widget build(BuildContext context) {
final appState = AppState.of(context);
return new Drawer(
child: new ListView(
padding: EdgeInsets.zero,
children: <Widget>[
new DrawerHeader(
child: new Text('MyNiT App'),
decoration: new BoxDecoration(
color: Colors.blue,
),
),
new ListTile(
title: new Text('Todo List'),
leading: new Icon(Icons.list),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Subscriptions'),
leading: new Icon(Icons.subscriptions),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Activity'),
leading: new Icon(Icons.timelapse),
onTap: () {
Navigator.pop(context);
},
),
new ListTile(
title: new Text('Profile'),
leading: new Icon(Icons.account_circle),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new AppState(
firebaseUser: appState.firebaseUser,
user: appState.user,
child: new ProfilePage(),
),
),
);
},
),
new ListTile(
title: new Text('Logout'),
leading: new Icon(Icons.exit_to_app),
onTap: () {
// Sign out user from app
FirebaseAuth.instance.signOut();
Navigator.of(context).pushAndRemoveUntil(
new MaterialPageRoute(builder: (context) => new LoginPage()),
ModalRoute.withName(null));
},
),
],
),
);
}
}
Try this Simple Bottom Bar
[import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>\[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
\];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>\[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
title: Text('School'),
),
\],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber\[800\],
onTap: _onItemTapped,
),
);
}
}][1]
Check this image for Sample

Resources