Flutter Snackbar Example

This Flutter tutorial demonstrates how to use the Snackbar widget to show a temporary message in your app. 

A Snackbar is a widget that displays a temporary message on the screen for a short period of time. 

It can be used to give feedback to the user, such as when an action is completed or when an error occurs.


import 'package:flutter/material.dart';

class SnackbarsDemo extends StatelessWidget {
  const SnackbarsDemo({super.key});

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: const Text('Snackbars'),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            ScaffoldMessenger.of(context).hideCurrentSnackBar(); // Hide any previous snackbar
            ScaffoldMessenger.of(context).showSnackBar(SnackBar( // Show a new snackbar
              content: const Text('This is snackbar'),
              action: SnackBarAction(
                label: 'Action',
                onPressed: () {
                  ScaffoldMessenger.of(context).hideCurrentSnackBar(); // Hide the current snackbar
                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar( // Show another snackbar
                      content: Text(
          child: const Text('Show Snackbar'),

Step by step code explanation:

Import the material package from Flutter.

Create a StatelessWidget called SnackbarsDemo.

In the build method, create a Scaffold widget with an AppBar and a Center child.

Inside the Center widget, create an ElevatedButton widget.

In the onPressed method of the ElevatedButton, first call ScaffoldMessenger.of(context).hideCurrentSnackBar() to hide any previous snackbar that might be showing.

Then, call ScaffoldMessenger.of(context).showSnackBar(SnackBar()) to show a new snackbar.

Inside the SnackBar widget, add a content property to display the message to the user.

Add an action property to the SnackBar widget to display a button that the user can press to take an action.

Inside the SnackBarAction widget, add a label property to display the text on the button.

Add an onPressed property to the SnackBarAction widget to handle the user pressing the button.

Inside the onPressed method of the SnackBarAction, call ScaffoldMessenger.of(context).hideCurrentSnackBar() to hide the current snackbar.

Then, call ScaffoldMessenger.of(context).showSnackBar(SnackBar()) to show another snackbar with a different message.

Save the file and run the app to see the snackbar in action.