DEV Community

Tirth Patel
Tirth Patel

Posted on • Originally published at Medium on

Snackbar, Snackbar Everywhere

Photo by Sam 🐷 on Unsplash

On Instagram when you bookmark a photo, it shows a snackbar on top of it. Today, we’re going to build a similar experience in Flutter without using any external dependencies & with minimal code!

So, let’s get started. 🍕🍫

👀 Demo

Demo

Create a fresh new flutter project:

flutter create snackbar_snackbar_everywhere
Enter fullscreen mode Exit fullscreen mode

After that, remove everything from main.dart & paste the following content:

import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: Scaffold(
body: ListView.builder(
itemBuilder: (_, index) {
final key = GlobalKey<ScaffoldState>();
return ListTile(
onTap: () {
key.currentState.showSnackBar(
SnackBar(
content: Text('$index bookmarked'),
),
);
},
title: Container(
margin: const EdgeInsets.all(16),
height: 200,
child: Scaffold(
key: key,
backgroundColor: Colors.black12,
body: Center(
child: Text(
index.toString(),
style: const TextStyle(
fontSize: 60,
),
),
),
),
),
);
},
),
),
),
);
view raw main.dart hosted with ❤ by GitHub
  • In this code, we start off with the MaterialApp & the main Scaffold.
  • The main Scaffold’s body contains a ListView.
  • Each ListTile consists of a Container whose child is another Scaffold.
  • Each of these child scaffold’s have a unique GlobalKey so that a SnackBar can be shown using that key whenever ListTile is tapped 🐍.
  • You can play around with the code on this dartpad ** 🎯**.

That’s it for this one. Thank you for reading this 💙

You can find the complete source code in the above gist or dartpad.

If you find this byte-sized post useful, press👏 button as many times as you can and share this post with others. You can leave your feedback/suggestions in the comments 💬 below.

For any other issues feel free to reach out to me via Twitter: https://twitter.com/piedcipher


Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay