Menu
CoddyTech

Show a SnackBar

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 10 of 34.

A SnackBar is a short message that slides up from the bottom of the screen and goes away on its own after about four seconds. Apps use it to say an action worked: Saved, Sent, Deleted.

ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(content: Text('Sent')),
);

Read it from the inside out: SnackBar(...) is the message, showSnackBar puts it on the screen, and ScaffoldMessenger.of(context) finds the part of the app that shows messages.

context is the widget's place in the tree, the one build receives. .of(context) searches up the tree from there. The messenger comes from MaterialApp, so it must be above you. HomePage is below MaterialApp, so its context finds it. MyApp's context is above it, and a SnackBar from there fails with "No ScaffoldMessenger widget found". That is another reason the screen has its own class.

challenge icon

Challenge

Easy

When Save is pressed, show a SnackBar that says Note saved.

Try it yourself

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Notes')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {},
          child: Text('Save'),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler