Display SnackBar on top of AlertDialog widget - flutter

I have an AlertDialog widget that will cause a SnackBar to display when you tap on its Text. The SnackBar currently displays behind the AlertDialog barrier, in the background. I want the Snackbar to display on top of the transparent AlertDialog barrier instead. Is the behavior that I'm seeking possible to achieve in Flutter? I have created a brand new Flutter app and included only the relevant code to illustrate the use-case below, as well as a screenshot.
Main.dart Gist
#override
Widget build(BuildContext context) {
WidgetsBinding.instance!.addPostFrameCallback((_) async {
showDialog(
context: context,
builder: (BuildContext dialogContext) => AlertDialog(
content: GestureDetector(
onTap: () {
ScaffoldMessenger.of(dialogContext).showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
);
});
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}

Update
Thanks to Amy, I realized that tapping on the barrier did not dismiss the dialog. Also, the code was causing to show multiple SnackBars due to the use of nested Scaffolds.
Check out the following model that fixes all issues:
showDialog
|
|
ScaffoldMessenger => "Set a scope to show SnackBars only in the inner Scaffold"
|
--- Builder => "Add a Builder widget to access the Scaffold Messenger"
|
--- Scaffold => "The inner Scaffold that is needed to show SnackBars"
|
--- GestureDetector => "Dismiss the dialog when tapped outside"
|
--- GestureDetector => "Don't dismiss it when tapped inside"
|
--- AlertDialog => "Your dialog"
Here is the implementation:
showDialog(
context: context,
builder: (context) => ScaffoldMessenger(
child: Builder(
builder: (context) => Scaffold(
backgroundColor: Colors.transparent,
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => Navigator.of(context).pop(),
child: GestureDetector(
onTap: () {},
child: AlertDialog(
content: GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
),
);
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
),
),
),
),
),
);
Old answer
ScaffoldMessenger shows SnackBar in the nearest descendant Scaffold. If you add another Scaffold before AlertDialog, it will use it instead of the root one which is left behind the dialog.
showDialog(
context: context,
builder: (BuildContext dialogContext) => Scaffold(
backgroundColor: Colors.transparent, // Make Scaffold's background transparent
body: AlertDialog(
content: GestureDetector(
onTap: () {
ScaffoldMessenger.of(dialogContext).showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
),
);

Instead of the SnackBar Use another_flushbar, It will Appear Above AlertDialog.
Flushbar(
backgroundColor: Colors.red,
message: S.of(context).choose_date,
duration: Duration(seconds: Constants.TOAST_DURATION),
).show(context);
Result:

The issue here is that showDialog uses the root navigator provided by MaterialApp. So when you show your dialog it is pushed completely over your scaffold. To solve this you need the navigator that is used to be a child of the scaffold that's showing the snackbars. So the following code adds this navigator, sets useRootNavigator to false to use this navigator, and importantly uses a BuildContext under the newly created navigator:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Navigator( //New navigator added here
initialRoute: '/',
onGenerateRoute: (setting) {
return MaterialPageRoute(
builder: (context) => Center(
child: Builder(builder: (context) {
WidgetsBinding.instance!
.addPostFrameCallback((_) async {
showDialog(
context: context,
useRootNavigator: false,//Dialog must not use root navigator
builder: (BuildContext dialogContext) =>
AlertDialog(
content: GestureDetector(
onTap: () {
ScaffoldMessenger.of(dialogContext)
.showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
);
});
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
]);
}),
));
}),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Result:
Note that this solution does constrain the dialog size a bit and the app bar and floating action button is above the content, which may be undesirable. This can be solved just by adding another scaffold below the newly created navigator and moving those appbar/FAB properties down as desired. Example with AppBar below the modal:
#override
Widget build(BuildContext context) {
return Scaffold(
body: Navigator(
initialRoute: '/',
onGenerateRoute: (setting) {
return MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Builder(builder: (context) {
WidgetsBinding.instance!
.addPostFrameCallback((_) async {
showDialog(
context: context,
useRootNavigator: false,
builder: (BuildContext dialogContext) =>
AlertDialog(
content: GestureDetector(
onTap: () {
ScaffoldMessenger.of(dialogContext)
.showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
);
});
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
]);
}),
)));
}),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Result:

hope this is what you are looking for
import 'package:flutter/material.dart';
class SnackOverDialog extends StatefulWidget {
SnackOverDialog({Key? key}) : super(key: key);
#override
_SnackOverDialogState createState() => _SnackOverDialogState();
}
class _SnackOverDialogState extends State<SnackOverDialog> {
final GlobalKey<ScaffoldState> _scaffoldkey = new GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
///* show snack
_snackbar(BuildContext context) {
_scaffoldkey.currentState!.showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
}
///* dialog
_dialog(BuildContext context) {
WidgetsBinding.instance!.addPostFrameCallback((_) async {
showDialog(
context: context,
builder: (BuildContext dialogContext) => AlertDialog(
content: Scaffold(
key: _scaffoldkey,
body: GestureDetector(
onTap: () {
_snackbar(dialogContext);
},
child: Center(
child: Text('Show SnackBar!'),
),
),
),
),
);
});
}
return Scaffold(
appBar: AppBar(
title: Text("SNackBarOVerDialog"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _dialog(context),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Related

flutter: Can I adjust the width or height of the CupertinoAlertDialog(iOS style)?

I'm new in flutter. I want a iOS style app so I use CupertinoAlertDialog. But I want to customize its height and width. Is that possible? Here is what I have done.
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: RaisedButton(
child: Text("Pick Me !!!"),
onPressed: () {
showDialog(
context: context,
builder: (_) => Center(
child: CupertinoAlertDialog (
title: new Text("drop out"),
content: new Text("quit the window"),
actions: <Widget>[
FlatButton(
child: Text('Cancle!'),
onPressed: () {
Navigator.pop(_);
},
),
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.pop(_);
},
)
],
),
)
);
},
)
),
);
}

How to display SnackBar in Flutter?

I want to display a SnackBar in my Flutter app. I have read the docs and copyed it:
The body of my scaffold:
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Osztályok"),
leading: Padding(
padding: const EdgeInsets.only(left: 5.0),
child: IconButton(
icon: Icon(Icons.exit_to_app, color: Colors.white70),
onPressed: () {
authService.signOut();
authService.loggedIn = false;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GoogleSignUp()));
})),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 5.0),
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.add_circle_outline,
color: Colors.white70),
onPressed: () {
createPopup(context);
}),
// IconButton(
// icon: Icon(Icons.search, color: Colors.black38),
// onPressed: null),
],
)),
],
),
The SnackBarPage class:
class SnackBarPage extends StatelessWidget {
void jelszopress(TextEditingController jelszoController, BuildContext context) async{
var jelszo;
DocumentReference docRef =
Firestore.instance.collection('classrooms').document(globals.getid());
await docRef.get().then((value) => jelszo= (value.data['Jelszo']) );
if (jelszo == jelszoController.text.toString()){
Navigator.push(context,
MaterialPageRoute(builder: (context) => InClassRoom()));
}
else{
Navigator.pop(context);
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
Scaffold.of(context).showSnackBar(snackBar);
}
}
Future<String> jelszoba(BuildContext context) {
TextEditingController jelszoController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add meg a jelszót'),
content: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: TextField(
controller: jelszoController,
decoration: InputDecoration(hintText: "Jelszó")
)
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('Mehet'),
onPressed: () {
jelszopress(jelszoController, context);
},
)]);
}
);
}
var nevek;
var IDS;
SnackBarPage(this.nevek, this.IDS);
#override
Widget build(BuildContext context){
return ListView.builder(
itemCount: nevek.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {
globals.setid(IDS[index]);
jelszoba(context);
},
title: Text(nevek[index]),
),
);
},
) ;
}
}
But my cody doesn't display the SnackBar. I tried the solution of this question: How to properly display a Snackbar in Flutter? but adding a Builder widget didn't help.
"Scaffold.of(context)" has been deprecated, will return null. Now use "ScaffoldMessenger.of(context)". As per Flutter documentation.
#override
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () { },
),
));
},
child: const Text('SHOW SNACK'),
),
),
);
}
NOTE: Make sure your main.dart overrided build() function should return "MaterialApp" as a widget, such as:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// Must be MaterialApp widget for ScaffoldMessenger support.
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyDashboard(),
);
}
}
So based on the error, it would seem that the context passed in Snackbar.of() is not the correct context. This would make sense based on 1 & 2; and summary copied below:
Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.build or State.build function. (And similarly, the parent of any children for RenderObjectWidgets.)
In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method.
So this means that the build context you are passing in jelszoba(context) function is not the build context you need and is actually the build context of the widget that is instantiating the Scaffold.
So How to Fix:
To fix this wrap your Card widget in your SnackbarPage in a Builder widget and pass the context from it, to the jelszoba(context) method.
An example from 1 I post below:
#override
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
appBar: AppBar(title: Text('Demo')),
body: Builder(
builder: (BuildContext context) {
return FlatButton(
child: Text('BUTTON'),
onPressed: () {
// here, Scaffold.of(context) returns the locally created Scaffold
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Hello.')
));
}
);
}
)
);
}
You can normally use snack bar in the Bottom Navigation bar in this way. However, if you want to show it in the body, then just copy the code from Builder and paste it in the body of the scaffold.
Scaffold(bottomNavigationBar: Builder(builder: (context) => Container(child: Row(children: <Widget>[
Icon(Icons.add_alarm), Icon(Icons.map), IconButton(icon: Icon(Icons.bookmark),
onPressed:() {
Scaffold.of(context).showSnackBar(mySnackBar);
final mySnackBar = SnackBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, duration: Duration(seconds: 1),
content: Text(
'Article has been removed from bookmarks',
),);
}
),
],
),
),
),
);
Note: In the behaviour property of SnackBar, you can just leave it empty. But the problem with that is "If you have Curved Navigation Bar or you have a floating action button above the bottom navigation bar, then the snackbar will lift these icons (or FAB ) and will affect the UI". That's why SnackBar.floating is more preferred as it is more capatible with the UI.
But you can check and see on your own which suits you the best.

How to display a card on tapping a FAB?

So this is what I got so far. Basically, I want to display the card once the user taps on the FAB. Now, when I tap on the FAB, there's no response.
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.exit_to_app),
onPressed: () => logoutUser().then((value) =>
Navigator.of(context).pushReplacementNamed('/SignIn')),
)
],
title: Text('TODO'),
),
body: Container(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add), onPressed: () => displayCard()),
);
}
Widget displayCard() {
return Center(
child: Card(
color: Colors.blue,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.album),
title: Text('The Enchanted Nightingale'),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
],
),
),
);
}
Right now, you're returning a Widget to your onPressed function, which is a VoidCallBack. It won't do anything with the Widget it receives back from displayCard().
Consider using a Dialog popup. Replace your widget displayCard() with something like the following.
void displayCard(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("The Enchanted Nightingale"),
content: Text("Music by Julie Gable. Lyrics by Sidney Stein."),
actions: <Widget>[
FlatButton(
child: Text("Dismiss"),
onPressed: () {
//remove the dialog popup
Navigator.of(context).pop();
}
)
]
);
}
);
}
Then, update your floatActionButton code to pass context as a parameter
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add), onPressed: () => displayCard(context)),

How do I set the distance between snackbar and floating action button?

How do I set the distance between snackbar and floating action button?
you can't set it !! it's the same as from the bottom plus the SnackBar height .
but if you want to adjust it you may not use the FAB from the Scaffold but instead make the body a Stack and the latest layer is your FAB and wrap it inside a AnimatedPositioned so you can animate it with the proper distance from the bottom as you want .
Are you tried
floatingActionButton: Column(mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [
FloatingActionButton(
onPressed: _doOrder,
mini: false,
elevation: 10,
child: Icon(EvaIcons.shoppingBagOutline),
),
Container(
height: 50,
)
]),
If you want the FloatingActionButton to always have a bottom padding, you could just wrap it with a Padding widget like this:
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: Padding(
padding: EdgeInsets.only(bottom: 40.0),
child: FloatingActionButton(
onPressed: () {},
),
),
appBar: AppBar(
title: Text('SnackBar'),
),
body: Builder(
builder: (context) => RaisedButton(
onPressed: () => _displaySnackBar(context),
child: Text('Show SnackBar'),
),
),
);
}
If you want the FloatingActionButton to have a new padding when the SnackBar is visible, you could change the padding when you show the SnackBar like this:
double _fabPadding = 0.0;
_displaySnackBar(BuildContext context) {
final snackBar = SnackBar(content: Text('SnackBar'));
setState(() {
_fabPadding = 40.0;
});
Scaffold.of(context).showSnackBar(snackBar).closed.then((_) {
setState(() {
_fabPadding = 0.0;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: Padding(
padding: EdgeInsets.only(bottom: _fabPadding),
child: FloatingActionButton(
onPressed: () {},
),
),
appBar: AppBar(
title: Text('SnackBar'),
),
body: Builder(
builder: (context) => RaisedButton(
onPressed: () => _displaySnackBar(context),
child: Text('Show SnackBar'),
),
),
);
}
Edit: If you want to avoid the SnackBar push the position of the FloatingActionButton you could set the behavior property of the SnackBar to SnackBarBehavior.floating
SnackBarBehavior
floating → const SnackBarBehavior This behavior will cause SnackBar to
be shown above other widgets in the Scaffold. This includes being
displayed above a BottomNavigationBar and a FloatingActionButton.
Trying to set : behavior: SnackBarBehavior.floating
It may worked
SnackBar(behavior: SnackBarBehavior.floating, content: Padding(child: Text(message),
padding: EdgeInsets.only(bottom: 30),)));
You can attach the snackbar to the scaffold with a key.
eg:-
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
void showSnackBar(String text) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(
text,
textAlign: TextAlign.center,
),
duration: Duration(seconds: 0, milliseconds: 750),
));
}
And then add the key to the scaffold:
Scaffold(
key: _scaffoldKey,
...
);
You can now call this function from anywhere.

How to pass a variable reference between different routes?

Im writing a simple gamebook game in flutter with menu, game and options route. In option route there is button that on pressed should delete all saved games.
Right at this moment Im loading saved games on application launch from SharedPreferences. Right after loading them I set up boolean _savedGame that im using in 'Continue' button in menu route and 'Delete saved games' button in options route to activate or deactivate them. The whole problem is - i dont know how to change variables in menu route from option route. When im creating option route I give it _savedGame so that it knows if it should render active or deactivated button.
PS. Yes, I know that right now im sending option route a copy of _savedGame variable.
Menu route option page button.
RaisedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OptionsPage(_savedGame),
),
),
Option page
class OptionsPageState extends State<OptionsPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Options",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.blueGrey[900],
),
body: Container(
alignment: Alignment.center,
color: Colors.cyan,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child:
Text('Delete saved games', style: TextStyle(fontSize: 40)),
onPressed:
widget.isGameSaved ? () => _showWarning(context) : null,
),
const SizedBox(height: 30),
RaisedButton(
child: Text('Back', style: TextStyle(fontSize: 40)),
onPressed: () {
Navigator.pop(context);
},
),
])),
),
);
}
Future<void> _showWarning(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Are you sure you want to delete saved game?'),
actions: <Widget>[
FlatButton(
child: Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Yes'),
onPressed: () {
saveGame('empty');
Navigator.of(context).pop();
setState(() {
widget.isGameSaved = false;
});
},
),
],
);
},
);
}
}
How do I "setState" for variables in different routes?
What you could do is have an InheritedWidget (call it say GameStateWidget) above your Navigator (or MaterialApp if you're using its navigator). In the InheritedWidget have a ValueNotifier, say savedGame that has the value you want to share.
Then in the route where you need to set the value
GameStateWidget.of(context).savedGame.value = ...
And in the route where you need the value
ValueListenableBuilder(
valueListenable: GameStateWidget.of(context).savedGame,
builder: (context, savedGameValue, child) => ...
)