I want to show SnackBar pop-up once per build of a certain stateful page. This is a Flutter web project. Any help will be appreciated.
Asked
Active
Viewed 1,255 times
0
-
`once per build` when widget update or on just when ever build methods get called? – Md. Yeasin Sheikh Jun 03 '22 at 14:08
-
Either ways is cool as I'm adding this only for landing page – Delwinn Jun 03 '22 at 14:09
3 Answers
0
i guess this is what you meant
Stafeful Widget {
Widget build() {
showsnackbar()
return someWIdget();
}

Sanketh B. K
- 759
- 8
- 22
-
1ty for your time, but I fixed it. And this will probably give out an error about setState() called before build() – Delwinn Jun 03 '22 at 13:31
-
-
0
Basically, I am using .addPostFrameCallback
it will show after the frame is build.
_showSnackBar() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("SnackBar")));
});
}
And place _showSnackBar()
inside initState show snackeBar once.
@override
void initState() {
super.initState();
_showSnackBar();
}
And place _showSnackBar()
under build method to show snackeBar every build
Widget build(BuildContext context) {
_showSnackBar();
......

Md. Yeasin Sheikh
- 54,221
- 7
- 29
- 56
-
I tried this on flutter web, the snackbar keeps on popping up all the time. – Delwinn Jun 03 '22 at 16:45
-
It is because build method can call multiple times. If you just want single time snack bar, place `_showSnackBar();` inside initState. – Md. Yeasin Sheikh Jun 03 '22 at 17:25
-
initstate wouldn't have the scaffold context,will raise an error. My try did – Delwinn Jun 04 '22 at 03:30
-
Did you run it? It will get context because of `addPostFrameCallback`. – Md. Yeasin Sheikh Jun 04 '22 at 04:40
0
This is an alternative
bool snackBarShowed = false;
in top-level code
I put this inside the build method
if (snackBarShowed) {
} else {
Future.delayed(Duration.zero, () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
action: SnackBarAction(
label: 'Ok',
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
backgroundColor: Colors.black87,
content: Text(
'Use top-left logo to move to previous screen',
style: body.copyWith(
color: Colors.white,
),
)));
});
snackBarShowed = true;
}

Delwinn
- 891
- 4
- 19