In this Flutter code showSnackBar()
doesn’t work. I don’t know how to use the two keys (_scaffoldStateKey
and _scaffoldMessengerKey
) at the same time. How should I correct it?
class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
final GlobalKey<ScaffoldState> _scaffoldStateKey= GlobalKey();
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldStateKey,
appBar: AppBar(
title: const Text("A test app"),
),
body: Center(
child: Column(
children: [
Builder(
builder: (context) {
return ElevatedButton(
onPressed: () {
_scaffoldStateKey.currentState?.openDrawer();
},
child: const Text("Open drawer 1"),
);
},
),
Builder(builder: (context) {
return ElevatedButton(
onPressed: () {
_scaffoldStateKey.currentState?.openDrawer();
},
child: const Text("Open drawer 2"),
);
}),
Builder(
builder: (context) {
return ElevatedButton(
onPressed: () { //doesn't work
_scaffoldMessengerKey.currentState?.showSnackBar(
const SnackBar(
content: Text("Here is a snackbar")),
);
},
child: const Text("Show snackbar"),
);
},
),
],
),
),
drawer: const Drawer(),
);
}
}
3
Answers
Try this!
You can show snackbar without using
_scaffoldMessengerKey
key.Happy coding🧑💻.
You don’t need to pass any key to show the snack bar in Flutter. Just use the below code –
For more details https://docs.flutter.dev/cookbook/design/snackbars