I have a SnackBar
that tell me when I click on the button that is on it I need to close it. I tried to write the ScaffoldMessenger.of(context).hideCurrentSnackBar()
method, but it gives an error, probably because I call it inside the showSnackBar method. Tell me, how can I close the SnackBar
by clicking on the Refresh button?
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
duration: const Duration(seconds: 3),
backgroundColor: Colors.transparent,
elevation: 0,
content: SystemMessagesSnackBar(
message: 'No internet access. Check your connection',
textButton: 'Refresh',
onPressed: ScaffoldMessenger.of(context).hideCurrentSnackBar(),
icon: SvgPicture.asset(constants.Assets.no_connection),
),
),
);
snackbar
class SystemMessagesSnackBar extends StatelessWidget {
const SystemMessagesSnackBar(
{Key? key,
required this.message,
required this.textButton,
this.icon,
this.onPressed})
: super(key: key);
final String message;
final String textButton;
final SvgPicture? icon;
final Function()? onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 80,
child: Stack(
children: [
Container(
padding: const EdgeInsets.only(left: 16),
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: constants.Colors.purpleDark,
),
child: Row(
children: [
icon != null
? Expanded(
flex: 1,
child: icon!,
)
: const SizedBox(width: 8),
Expanded(
flex: 4,
child: Text(
message.toString(),
style: constants.Styles.smallBookTextStyleWhite,
textAlign: TextAlign.start,
),
),
TextButton(
onPressed: onPressed,
child: Text(
textButton,
style: constants.Styles.tinyBookTextStyleWhite,
),
),
],
),
),
),
],
),
);
}
}
CodePudding user response:
Add a key to the scaffold and use hideCurrentSnackBar
scaffoldKey.currentState.hideCurrentSnackBar();
Or you can also use
ScaffoldMessenger.of(context).hideCurrentSnackBar()
CodePudding user response:
While you are doing onPressed: myMethod(),
It's directly calling the method,
You can do
content: SystemMessagesSnackBar(
message: 'No internet access. Check your connection',
textButton: 'Refresh',
onPressed: ScaffoldMessenger.of(context).hideCurrentSnackBar,
),
or
onPressed: () =>
ScaffoldMessenger.of(context).hideCurrentSnackBar(),
CodePudding user response:
you can Use This
final Snackbar snackBar = Snackbar.make(findViewById(android.R.id.content), "Snackbar Message", Snackbar.LENGTH_LONG);
snackBar.setAction("Discard", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call your action method here
snackBar.dismiss();
}
});
snackBar.show();