-0.1 C
New York
Wednesday, November 29, 2023

Flutter: Showing SnackBar with ScaffoldMessenger

Flutter is becoming increasingly popular and used by many developers around the world to create great apps. At the time of writing it is one of the most popular open-source repositories on GitHub with approximately 140k stars.

Flutter 2 has been released for a while and has brought several changes, including a new widget named ScaffoldMessenger and the way we display SnackBars in our applications. Advertisements

The Old Ways (Now Depreciated)

In the old days, we used to display SnackBar with the 2 following approaches.

The first one is using Scaffold.of(context).showSnacBar(/*Â…*/) like this:

Scaffold.of(context).showSnackBar(SnackBar(
    content: Text('I am a snack bar!'),
));

The second way is showing SnackBar with a key as shown below:

final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

void _show() {
    _scaffoldKey.currentState.showSnackBar(SnackBar(
      content: Text("Hello"),
    ));
}

AdvertisementsMany Flutter newcomers are likely to encounter the error below when showing a snack bar with the old-fashioned approaches:

Scaffold.of() called with a context that does not contain a Scaffold

ScaffoldMessenger can help you get rid of this problem.

Using ScaffoldMessenger

ScaffoldMessenger provides APIs for displaying snack bars in a neat and simple way.

Advertisements

With the ScaffoldMessenger class, we now can call showSnackBar() inside or outside the build() function without worry about context. Both implementations below are working fine.

1. Call showSnackBar() inside build():

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text("Hi, I am a snack bar!"),
            ));
          },
          child: Text('Show SnackBar'),
        ),
      ),
    );
}

2. Call showSnackBar() outside build():

void _show() {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text("Hi, I am a snack bar!"),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _show,
          child: Text('Show SnackBar'),
        ),
      ),
    );
}

The Complete Example

Preview:

The full code:

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  void _show() {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text("Hi, I am a snack bar!"),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _show,
          child: const Text('Show SnackBar'),
        ),
      ),
    );
  }
}

Conclusion

This article has walked you through a few aspects of using SnackBar in modern Flutter. If you would like to learn more exciting and new things about mobile development, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles