I am new to flutter,Here I can’t find why my snackbar is not showing in the ui.I tried exactly like the documentation .
Scaffold(
body: Center(
child: ElevatedButton(
child: const Text('Show SnackBar'),
onPressed: () {
final snackBar = SnackBar(
content: const Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {},
),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
),
),
));
3
Answers
This is a sample code for displaying SnackBar in flutter
Photo:
Try the below code, You may missed forgot to wrap your scaffold
with
MaterialApp();
The problem is, that the call to
ScaffoldMessenger.of(context).showSnackBar(snackBar)
makes Flutter search the widget tree for ancestors of typeScaffoldMessenger
and it’s not able to find one.This happens, because you pass in the
BuildContext
of the widget under which the Scaffold is declared. But it searches in the opposite direction.One solution to this is, to wrap the call to
ScaffoldMessenger.of
in aBuilder
widget, wich introduces a newBuildContext
. Then Flutter is able to find a ScaffoldMessenger in the widget tree and use it to show the SnackBar.Check out the
Builder
documentation, it explains everything about those.of()
methods: https://api.flutter.dev/flutter/widgets/Builder-class.html