Open In App

Flutter – Flashbar, Toast and Dialog using Flash

Last Updated : 02 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The flutter community is making Flutter strong and popular through its libraries making the development faster and simpler. Flash is a Flutter library that serves multiple purposes. One can create  Snackbars, toasts, and dialogs with it. Flutter does not have Toast by default. So, using Flash library it can be created. With the Flash package, you can streamline everything using only a single package. The best part is it can be customized as per the requirements. You don’t need to work with different packages for snackbar or toast or dialog. It can be done easily with Flash. In this article, we are going to learn how we can create all this using one package – Flash.

  • Add dependency

Let us add dependency in pubspec.yaml file, before we move to the coding part.

Dart




dependencies:
  flash: ^2.0.3+1


Don’t forget to configure it by running pub get in the terminal of your working IDE.

  • Import the library

To use the library, of course, we need to import it in the main.dart or whichever file you are going to make use of it.

Dart




import 'package:flash/flash.dart';


Dialogs:

It was always a boring task to create pop-ups with default showDialog. However, showing dialogs is a  simple task. In the below-shown code is defined the _showDialogFlash() that shows the dialog by invoking showFlashDialog(). We can pass a bunch of arguments to this function like title, negativeActionBuilder, etc. 

Dart




void _showDialogFlash() {
    context.showFlashDialog(
      title: Text('Flash Dialog'),
      content: Text('This is the simplest dialog you can create with Flash.'),
      negativeActionBuilder: (context, controller, _) {
        return TextButton(
          onPressed: () {
            controller.dismiss();
          },
          child: Text("CLOSE"),
        );
      },
    );
  }
}


Then, this function can be invoked whenever you want it to. For Example, create a button that will invoke _showDialogFlash() when pressed.

Dart




ElevatedButton(
      onPressed: () => _showDialogFlash(),
      child: Text('Simple Dialog'),
 ),


Toasts:

Toasts are just short messages pop-ups that remain visible even when the app is not foreground. Now, we can create toast in Flutter easily using the Flash library. To create the Toast, create a child and define a global key. Wrap the child with the Toast, and then pass to FlashTheme which will be returned as a child. Then, simply invoke the showToast() on the context, and use its properties like the message, duration, etc. We created an ElevatedButton named “Toast” which when pressed shows the toast in the context of the current screen.

Dart




import 'package:flash/flash.dart';
import 'package:flutter/material.dart';
  
void main() => runApp(App());
  
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      builder: (context, _) {
        var child = _!;
        final navigatorKey = child.key as GlobalKey<NavigatorState>;
        child = Toast(child: child, navigatorKey: navigatorKey);
        child = FlashTheme(
          child: child,
          flashDialogTheme: const FlashDialogThemeData(),
        );
        return child;
      },
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: FlashDemo(),
    );
  }
}
  
class FlashDemo extends StatefulWidget {
  @override
  _FlashDemoState createState() => _FlashDemoState();
}
  
class _FlashDemoState extends State<FlashDemo> {
  GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksForGeeks"),
        centerTitle: true,
      ),
      key: _key,
      body: Container(
          child: Center(
        child: ElevatedButton(
          onPressed: () =>
              context.showToast('You have 10 minutes left in the meeting.'),
          child: Text('Toast'),
        ),
      )),
    );
  }
}


Output:

Flashbar:

It is the beauty of the Flash library that with a single function, you can create different types of snackbars. Flashbar is now not limited to ground level, you can show it at the top of the screen or bottom or you can even customize it giving it margin, background color, etc. The unique point of creating a snackbar with Flash is you can even give input in the snackbar that we are calling flashbar, with the button or icon for accepting it. In the further article, we are going to look at different types of flashbars we can create with Flash. 

The Basic Flashbar:

The simple snackbar using Flash can be created just using the _showBasicFlash() function. It takes the builder as a property that returns Flash which wraps Flashbar as a child. Then we can give any content we want inside the flashbar. The _showBasicFlash() takes two parameters one cannot be null, that is duration but behavior can be skipped as it is already defined as floating. If we don’t pass duration to the function or fix the duration in the showFlash() function, the flashbar will remain on the screen until the app is closed.

Dart




void _showBasicFlash({
    Duration? duration,
    flashStyle = FlashBehavior.floating,
  }) {
    showFlash(
      context: context,
      duration: duration,
      builder: (context, controller) {
        return Flash(
          controller: controller,
          behavior: flashStyle,
          position: FlashPosition.bottom,
          horizontalDismissDirection: HorizontalDismissDirection.horizontal,
          child: FlashBar(
            content: Text('This is a basic flashbar'),
          ),
        );
      },
    );
  }


Output:

Top Flashbar:

Well, if we want the snackbar to take the entry from the top or we can say pop-up like notifications which are important in many applications nowadays. This could be done in a simple way with Flash. Again just using showFlash() function. But we need to tell what position we want- bottom or top or values can be passed to locate its position. We created a function _showTopFlash() that invokes showFlash() function. We passed the behavior of flash with FlashBehavior, used FlashBehavior.fixed we can also make it float. We gave it certain styling and also created a TextButton “DISMISS” to dismiss the flashbar, we can do whatever we want as per the requirements or creativity.

Dart




void _showTopFlash({FlashBehavior style = FlashBehavior.fixed}) {
    showFlash(
      context: context,
      duration: const Duration(seconds: 2),
      persistent: true,
      builder: (_, controller) {
        return Flash(
          controller: controller,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          barrierColor: Colors.black38,
          barrierDismissible: true,
          behavior: style,
          position: FlashPosition.top,
          child: FlashBar(
            title: Text('Hey User!'),
            content: Text('This is the top Flashbar!'),
            primaryAction: TextButton(
              onPressed: () {},
              child: Text('DISMISS',
                          style: TextStyle(color: Colors.blue)),
            ),
          ),
        );
      },
    );
  }


Output:

Customized Bottom Flashbar:

Flashbar doesn’t stop here when it comes to its properties. Here, in the given example code we customized the flashbar by giving it gradient colors along with the information icon and TextButton “DISMISS” as a primaryAction property of Flash which dismisses the flashbar when pressed. Add animations to the flashbar, style it, it contains many properties which can fulfill all the requirements.

Dart




void _showCustomFlash() {
    showFlash(
      context: context,
      builder: (_, controller) {
        return Flash(
          controller: controller,
          behavior: FlashBehavior.floating,
          position: FlashPosition.bottom,
          borderRadius: BorderRadius.circular(8.0),
          borderColor: Colors.blue,
          backgroundGradient: LinearGradient(
            colors: [Colors.pink, Colors.red],
          ),
          forwardAnimationCurve: Curves.easeInCirc,
          reverseAnimationCurve: Curves.bounceIn,
          child: DefaultTextStyle(
            style: TextStyle(color: Colors.white),
            child: FlashBar(
              title: Text('Hello Flash'),
              content: Text('You can put any message of any length here.'),
              indicatorColor: Colors.blue,
              icon: Icon(
                Icons.info_outline_rounded,
                color: Colors.white,
              ),
              primaryAction: TextButton(
                onPressed: () => controller.dismiss(),
                child: Text('DISMISS', style: TextStyle(color: Colors.white)),
              ),
            ),
          ),
        );
      },
    );
  }


Output:

Flashbar with Input:

In this we are going to know about the interesting property of Flash, we can even take input inside the Flashbar. Yes, it will make UI more appealing. Whenever there is an error along with an error you might want to redirect the user to a help page or anything else, it can be done using a simple flashbar created using Flash. The _flashWithInput() function that further calls showFlashBar() in the context, and created a TextFormField to which editingController is given as a controller and using primaryActionBuilder to show an IconButton which when pressed will perform some function. It’s easy to customize it as per needs. 

Dart




void _flashWithInput() {
    TextEditingController editingController = TextEditingController();
    context.showFlashBar(
      barrierColor: Colors.blue,
      borderWidth: 3,
      behavior: FlashBehavior.fixed,
      forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
      title: Text('Hello from Flash'),
      content: Column(
        children: [
          Text('You can put any message of any length here.'),
          TextFormField(
            controller: editingController,
            autofocus: true,
          )
        ],
      ),
      primaryActionBuilder: (context, controller, _) {
        return IconButton(
          onPressed: () {
            print(editingController.text);
            editingController.clear();
          },
          icon: Icon(Icons.send, color: Colors.blue),
        );
      },
    );
  }


Output:

Complete Code for Flashbar:

Dart




import 'package:flash/flash.dart';
import 'package:flutter/material.dart';
  
void main() => runApp(App());
  
class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      builder: (context, _) {
        var child = _!;
        final navigatorKey = child.key as GlobalKey<NavigatorState>;
          
        // initializing a Toast and passing it in the FlashTheme
        child = Toast(child: child, navigatorKey: navigatorKey);
        child = FlashTheme(
          child: child,
          flashDialogTheme: const FlashDialogThemeData(),
        );
        return child;
      },
      title: 'Flash Tutorial',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("GeeksForGeeks"),
                     centerTitle: true),
      body: Container(
          padding: const EdgeInsets.all(20.0),
          child: Overlay(
              
            // with the help of overlay the background
            // will not go blur and the toast can lay
            // on the other widgets.
            initialEntries: [
              OverlayEntry(builder: (context) {
                return FlashDemo();
              }),
            ],
          )),
    );
  }
}
  
class FlashDemo extends StatefulWidget {
  @override
  _FlashDemoState createState() => _FlashDemoState();
}
  
class _FlashDemoState extends State<FlashDemo> {
    
  // creating a global Scaffold key
  GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _key,
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text('Flash Examples',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(
                
              // calling function to show the basic flashbar
              onPressed: () => _showBasicFlash(),
              child: Text('Basic Flashbar'),
            ),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                
              // show snackbar from top of the screen
              onPressed: () => _showTopFlash(),
              child: Text('Top Flashbar'),
            ),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                
              // customize the flashbar
              onPressed: () => _showCustomFlash(),
              child: Text('Bottom Flashbar'),
            ),
            SizedBox(
              height: 10,
            ),
            ElevatedButton(
                
              // take input inside flashbar
              onPressed: () => _flashWithInput(),
              child: Text('Input Flashbar'),
            ),
            ElevatedButton(
              onPressed: () =>
                
              // show toast simply calling showToast in the context
                  context.showToast('You have 10 minutes left in the meeting.'),
              child: Text('Toast'),
            ),
          ],
        ),
      ),
    );
  }
  
  void _showBasicFlash({
    flashStyle = FlashBehavior.floating,
  }) {
    showFlash(
      context: context,
      duration: Duration(seconds: 3),
      builder: (context, controller) {
        return Flash(
          controller: controller,
          behavior: flashStyle,
          position: FlashPosition.bottom,
          horizontalDismissDirection: HorizontalDismissDirection.horizontal,
          child: FlashBar(
            content: Text('This is a basic flashbar'),
          ),
        );
      },
    );
  }
  
  void _showTopFlash() {
    showFlash(
      context: context,
      duration: const Duration(seconds: 2),
      builder: (_, controller) {
        return Flash(
          controller: controller,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          barrierColor: Colors.black38,
          barrierDismissible: true,
          behavior: FlashBehavior.fixed,
          position: FlashPosition.top,
          child: FlashBar(
            title: Text('Hey User!'),
            content: Text('This is the top Flashbar!'),
            primaryAction: TextButton(
              onPressed: () {},
              child: Text('DISMISS', style: TextStyle(color: Colors.blue)),
            ),
          ),
        );
      },
    );
  }
  
  void _showCustomFlash() {
    showFlash(
      context: context,
      builder: (_, controller) {
        return Flash(
          controller: controller,
          behavior: FlashBehavior.floating,
          position: FlashPosition.bottom,
          borderRadius: BorderRadius.circular(8.0),
          borderColor: Colors.blue,
          backgroundGradient: LinearGradient(
            colors: [Colors.pink, Colors.red],
          ),
          forwardAnimationCurve: Curves.easeInCirc,
          reverseAnimationCurve: Curves.bounceIn,
          child: DefaultTextStyle(
            style: TextStyle(color: Colors.white),
            child: FlashBar(
              title: Text('Hello Flash'),
              content: Text('You can put any message of any length here.'),
              indicatorColor: Colors.blue,
              icon: Icon(
                Icons.info_outline_rounded,
                color: Colors.white,
              ),
              primaryAction: TextButton(
                onPressed: () => controller.dismiss(),
                child: Text('DISMISS', style: TextStyle(color: Colors.white)),
              ),
            ),
          ),
        );
      },
    );
  }
  
  void _flashWithInput() {
    TextEditingController editingController = TextEditingController();
    context.showFlashBar(
      barrierColor: Colors.blue,
      borderWidth: 3,
      behavior: FlashBehavior.fixed,
      forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
      title: Text('Hello from Flash'),
      content: Column(
        children: [
          Text('You can put any message of any length here.'),
          TextFormField(
            controller: editingController,
            autofocus: true,
          )
        ],
      ),
      primaryActionBuilder: (context, controller, _) {
        return IconButton(
          onPressed: () {
            print(editingController.text);
            editingController.clear();
          },
          icon: Icon(Icons.send, color: Colors.blue),
        );
      },
    );
  }
}


Output:

We hope you learned something new today and this article was helpful to you.



Similar Reads

Motion Toast Widget in Flutter
A Motion Toast widget in Flutter is a type of toast message that animates its appearance on the screen. It can be used to provide feedback or notifications to the user in a subtle, yet attention-grabbing way. One way to implement a Motion Toast in Flutter is to use the AnimatedContainer widget. You can use the AnimatedContainer to animate the size
3 min read
Flutter - How to Turn on Camera Flash
Flutter is a UI toolkit developed and maintained by Google. It was released in May 2017 to the public. It is now one of the most popular cross-platform development frameworks among beginners and experienced application developers. It has a straightforward learning curve and uses the Dart programming language for developing the applications. Every s
2 min read
Flutter - Creating Dialog in using GetX Library
When we want to show anything in the form of the dialog then we can create this Dialog using the GetX library in Flutter. When we normally create a dialog in flutter then it uses context and builder to create a Dialog. This is not a good practice for a developer to create Dialogs using contexts and builders. To overcome this problem, we can create
3 min read
Alert Dialog box in Flutter
Alert Dialog box informs the user about the situation that requires acknowledgment. Alert Box is a prompt that takes user confirmation. The very basic use of the alert box is used when we close the app, usually, we are notified with a prompt whether we want to exit or not. That's an alert box. The below-added code shows how to perform alert Dialog
3 min read
Flutter - Toggle the Visibility of an Alert Dialog
Alert Dialog is a very useful way to grab user interactions, here we use the Offstage widget to toggle (Hide/Show) the visibility of the Alert Dialog. The Offstage widget in Flutter is used to hide a widget from the user interface. It does this by laying out the child widget as if it was in the tree, but without painting anything, without making th
4 min read
Custom Toast in Android Using PoiziToast Library
A Toast provides information/feedback about an operation. It is a small popup that appears on the current activity UI and automatically disappears after a timeout. In this article, we will learn how to create customized Toast using PoiziToast Library in android. So, we will understand this by making a simple app to display customized Toast. What is
2 min read
Custom Toast in Android using Jetpack Compose
Toast messages are displayed within the android application to display several messages to the user. Toast messages are feedback messages which are displayed to the users on performing some action within the android application. In this article, we will look at How to add Custom styled toast in android using Jetpack Compose. Step by Step Implementa
8 min read
How to Create Balloon Toast Message in Android?
In this article, we are going to creating a balloon Toast. This Library is one of the popular features that is commonly used in most Android Apps. We can get to see this feature in most of the shopping and messaging apps. With the help of this feature, you can get a hint about what to do next in any app. Here in the output, we can see what we are g
2 min read
Different Ways to Add Image to Toast in Android
A Toast is a feedback message. It takes very little space for displaying while the overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If the user wants a permanently visible message, a Notification can be used. Another type of Toast is custom Toast, in which images can be used in
4 min read
How to Customize Toast in Android?
A Toast is a feedback message. It takes very little space for displaying and it is displayed on top of the main content of an activity, and only remains visible for a short time period. In this article, we will learn how to customize Toast in android. So, we will understand this by making a simple app to display a Toast. Step by Step Implementation
2 min read