Show SnackBar Messages on Top of the Screen in Flutter

The SnackBar widget in Flutter is a convenient widget to display flash messages at the bottom of the screen. However, what if you want to show these messages at the top? In this post, I will show you how to do it. I will also introduce a third-party package that simplifies the process even further.

1. Setting up Our SnackBar Widget

First, let us have a look at our starter’s code. I have set up our main.dart file to display a SnackBar message right away. See the code snippet of the main.dart file below:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'SnackBar Demo',
      home: MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SnackBar Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Show SnackBar'),
          onPressed: () => ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.red,
              content: Text(
                'This is a SnackBar message.',
                textAlign: TextAlign.center,
              ),
              duration: Duration(seconds: 2),
            ),
          ),
        ),
      ),
    );
  }
}

The code provides a basic Flutter application structure with a MyApp widget as the root widget. Inside the MyApp widget, we define a MyHomePage widget as the home page of our application. The home page consists of a Scaffold widget that provides the application structure with an AppBar and a body.

Within the body, we have placed an ElevatedButton widget. When the button is pressed, it triggers the onPressed callback, which displays a SnackBar using ScaffoldMessenger.of(context).showSnackBar function. The SnackBar has a red background color and displays the message “This is a SnackBar message” at the center. It will automatically disappear after 2 seconds.

As you can see the initial code allows us to show a SnackBar message. Let us proceed to display the SnackBar at the top of the screen instead of the default bottom position.

2. Displaying Our Snackbar on Top

To make the SnackBar appear on the top of our page, we need to add additional properties to our SnackBar widget. Here is the updated SnackBar:

SnackBar(
  backgroundColor: Colors.red,
  content: const Text(
    'This is a SnackBar message.',
    textAlign: TextAlign.center,
  ),
  duration: const Duration(seconds: 2),
  behavior: SnackBarBehavior.floating,
  margin: EdgeInsets.only(
    bottom: MediaQuery.of(context).size.height * 0.825,
  ),
),

In the code above, we have added the behavior property and set it to SnackBarBehavior.floating. This behavior allows the SnackBar to float above the screen.

To ensure that the SnackBar appears at the top, we set the margin property to position it accordingly. By calculating the height of the screen and taking 82.5% of its width MediaQuery.of(context).size.height * 0.825, we create a margin that leaves only a small portion at the bottom, effectively pushing the SnackBar to the top of the screen.

While the SnackBar message now shows up on the top, there is still one issue. Because the SnackBar message is dismissible, all the widgets behind it become noninteractive due to the applied margin to the SnackBar widget (82.5% of the screen).

3. Make the Underlying Widgets Interactable

To make the underlying widgets interactable, we need to add one more property to our SnackBar widget, see the code snippet:

SnackBar(
  backgroundColor: Colors.red,
  content: const Text(
    'This is a SnackBar message.',
    textAlign: TextAlign.center,
  ),
  duration: const Duration(seconds: 2),
  behavior: SnackBarBehavior.floating,
  margin: EdgeInsets.only(
    bottom: MediaQuery.of(context).size.height * 0.825,
  ),
  dismissDirection: DismissDirection.none,
),

By setting the dismissDirection property to DismissDirection.none, we disable the ability to dismiss the SnackBar by swiping it away. This ensures that the underlying widgets remain interactable even when the SnackBar is displayed.

As you can see it is now possible to click the button even though the SnackBar message is shown.

While the previously provided solution works, it feels like a bit of a hack, and it would be ideal if the SnackBar widget had a simpler solution. Unfortunately, as of now, it does not. However, there are alternative packages available that provide more straightforward ways to display SnackBar messages on top.

One such package is top_snackbar_flutter. It offers a user-friendly solution for displaying SnackBar widgets at the top of the screen. Let us see how to use it:

1. Run flutter pub add top_snackbar_flutter to add the package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  top_snackbar_flutter: ^3.0.0+1

2. Make sure that the package is added to your pubspec.yaml.

3. Import the package in our main.dart file and replace the ScaffoldMessenger.of(context).showSnackBar with the showTopSnackBar function:

import 'package:flutter/material.dart';
import 'package:top_snackbar_flutter/custom_snack_bar.dart';
import 'package:top_snackbar_flutter/top_snack_bar.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'SnackBar Demo',
      home: MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SnackBar Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Show SnackBar'),
          onPressed: () => showTopSnackBar(
            Overlay.of(context),
            const CustomSnackBar.error(
              message: 'This is a CustomSnackBar message',
              textStyle: TextStyle(color: Colors.white),
            ),
            displayDuration: const Duration(seconds: 2),
          ),
        ),
      ),
    );
  }
}

If you encounter issues with unrecognized imports, ensure that you run flutter pub get to ensure that the project recognizes the imports.

In the updated code snippet above, we added two imports:

  1. import 'package:top_snackbar_flutter/custom_snack_bar.dart'; to access the CustomSnackBar widget.
  2. import 'package:top_snackbar_flutter/top_snack_bar.dart'; to access the showTopSnackBar function.

We also replaced the ScaffoldMessenger.of(context).showSnackBar function with showTopSnackBar function to display a CustomSnackBar message. We pass a CustomSnackBar.error widget to the showTopSnackBar function with the desired message, and text style.

Furthermore, the showTopSnackBar function needs an OverlayState which we provided with Overlay.of(context) and we added the displayDuration property which is set to 2 seconds.

As you can see, the result is similar to before. However, this approach offers greater simplicity and visual appeal.

The top_snackbar_flutter package includes three preset styles: .error, .success, and .info. These presets allow you to easily customize the look of your SnackBar widgets. In the example above, we used the .error style. You can also use the .success and .info styles, as shown in the GIF below, to create different visual effects for your SnackBar widgets.

To learn more about this package, be sure to check out their documentation.

5. Conclusion

In this post, we explored different methods to display SnackBar messages at the top of the screen in Flutter. We started by adjusting the properties of the default SnackBar widget to achieve the desired positioning. We have seen that this works but it does not feel right and you might encounter problems.

To overcome this, I recommend using the top_snackbar_flutter package, which provides a simpler and more visually appealing solution.

By leveraging the showTopSnackBar function and the package’s presets such as .error, .success, and .info, you can easily customize the appearance of your SnackBar widgets.

Tijn van den Eijnde
Tijn van den Eijnde
Articles: 87

Leave a Reply

Your email address will not be published. Required fields are marked *