I am trying to create a custom snackbar. It includes a "setState" executed after the snackbar dismisses. But the setStat function doesn't work (i.e., snackBarIsOn = false;). The snackbar pops up and dismisses after 2 seconds. It is also supposed to change "snackBarIsOn" to "true" but it doesn't happen. I tested it in the main code without the method. It works as it is supposed to. I am suspicious about the type of "actionAfterClosed".
Please help me.
customSnackBar(
context: context,
content: 'Enter a Title.',
label: 'Close',
textColor: Colors.white,
snackBarAction: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
setState(() {
snackBarIsOn = false;
});
},
actionAfterClosed:
setState(() {
snackBarIsOn = false;
})
);
void customSnackBar(
{required BuildContext context,
required String content,
required String label,
required Color textColor,
required VoidCallback snackBarAction,
required **VoidCallback** actionAfterClosed}) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(
content: Text(content),
duration: const Duration(seconds: 2),
action: SnackBarAction(
label: label,
textColor: textColor,
onPressed: snackBarAction,
),
))
.closed
.then((_) =>
actionAfterClosed
);
}
CodePudding user response:
I believe this is the problem:
actionAfterClosed:
setState(() {
snackBarIsOn = false;
})
Here, you are telling flutter to run setState
, and then use whatever it returns as a callback, so it expects setState
to return a function to call after the snackbar closes, instead of calling setState
itself.
To fix this, you must use a function literal like you did for snackbarAction
:
actionAfterClosed:
() => setState(() {
snackBarIsOn = false;
})
The second problem I can find is here:
.closed
.then((_) =>
actionAfterClosed
);
You forgot the parenthesis! this way the function isn't running!
.closed
.then((_) =>
actionAfterClosed()
);