Open In App

Flutter – Flashbar, Toast and Dialog using Flash

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.



Last Updated : 02 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads