How to Create and Show Toast in Flutter

How to Create and Show Toast in Flutter

Toast in Flutter – To notify the user of an activity or event, a toast appears quickly at the bottom of the screen in Flutter application. After a few seconds, it disappears without user interaction.

to use toast there are several ways in flutter, here we provide an example below:

Show Fluttertoast Package

The Fluttertoast package makes it easy to make a toast in flutter app. In this case:

  • Add fluttertoast packages by adding this line to your pubspec.yaml:
dependencies:
  fluttertoast: ^8.2.1
  • You must import package fluttertoast flutter before you can use it in your code.
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
  • To show a toast, call the Fluttertoast.showToast() method with the desired toast message in flutter:
Fluttertoast.showToast(
  msg: "This is a toast message!",
  toastLength: Toast.LENGTH_SHORT,
  gravity: ToastGravity.BOTTOM,
  timeInSecForIosWeb: 1,
  backgroundColor: Colors.grey[600], //background color
  textColor: Colors.white, //text color
  fontSize: 16.0 //font size
);

The toast message “This is a toast message!” will appear at the screen’s bottom for a full second.

By modifying the parameters supplied to the showToast() method, the toast can be made to look and behave as desired. The toast’s duration, placement, background color, text color, and font size are just some of the customizable options.

Full Code

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'How to Create and Show Toast in Flutter',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Fluttertoast.showToast(
                msg: "This is a toast message!",
                toastLength: Toast
                    .LENGTH_SHORT, //toast message toastlength toast.length short or long
                gravity: ToastGravity.BOTTOM,
                timeInSecForIosWeb: 1,
                backgroundColor: Colors.deepPurple[600], //background color
                textColor: Colors.white, //text color
                fontSize: 16.0 //font size
                );
          },
          child: Text('Show Dialog'),
        ),
      ),
    );
  }
}

Output

Show Toast in Flutter with ScaffoldMessenger and SnackBar widget

ScaffoldMessenger and SnackBar are available. An example:

ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                behavior: SnackBarBehavior.floating,
                padding: EdgeInsets.all(10),
                backgroundColor: Colors.deepPurple,
                content: Center(child: Text('Your message here')),
                duration: Duration(seconds: 2), // Optional
              ),
            );

You can customize the toast by replacing “Your message here” with your own text. The toast’s time to expire is controlled by the duration argument, which is optional. The default time it stays on screen is 2 seconds.

Show Toast with Overlay and OverlayEntry widget

Flutter Overlay and OverlayEntry widgets can show a personalized toast message over the current screen. An example:

import 'package:flutter/material.dart';

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

OverlayEntry overlayEntry = OverlayEntry(
  builder: (BuildContext context) => Positioned(
      top: MediaQuery.of(context).size.height * 0.75,
      width: MediaQuery.of(context).size.width,
      child: Material(
        color: Colors.transparent,
        child: Container(
          alignment: Alignment.center,
          child: Text('Your message here'),
        ),
      )),
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'How to Create and Show Toast in Flutter',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Overlay.of(context).insert(overlayEntry);

// Hide the overlay entry after a certain period of time.
            Future.delayed(Duration(seconds: 3), () {
              overlayEntry.remove();
            });
          },
          child: Text('Show Toast'),
        ),
      ),
    );
  }
}

Calling Overlay.of(context).insert(overlayEntry). insert(overlayEntry) and hidden after a given time using Future.delayed and overlayEntry.remove(). The Overlay widget and OverlayEntry widget can display messages and widgets on top of the current screen.

Output

Show Toast in Flutter

Show Toast with AnimatedContainer

by animating the message’s show and hide using the AnimatedContainer widget. Example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'How to Create and Show Toast in Flutter',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _showToast = false;

  void showToast() {
    setState(() {
      _showToast = true;
    });
    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        _showToast = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Row(children: [
            Image.asset(
              'assets/logo.png',
              height: 30,
            ),
            Text('flutterflux.com')
          ]),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              showToast();
            },
            child: Text('Show Toast'),
          ),
        ),
        bottomNavigationBar: Padding(
          padding: EdgeInsets.only(bottom: 50),
          child: _showToast
              ? AnimatedContainer(
                  duration: Duration(seconds: 1),
                  decoration: BoxDecoration(
                    color: Colors.deepPurple,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  margin: EdgeInsets.symmetric(horizontal: 20),
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  child: Text(
                    'Your message here',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                    ),
                  ),
                )
              : SizedBox.shrink(),
        ));
  }
}

The toast message will only be shown if the _showToast variable is set to true. When the showToast() method is invoked, _showToast is toggled to the true state and a timer is activated to reset it to the false state after three seconds. With an if statement, we can control when the toast appears, and the AnimatedContainer widget will animation its appearance and disappearance. By changing the AnimatedContainer settings like background color, border radius, and padding, the toast message can be made to look exactly how you want it to.

Output

How to Create and Show Toast in Flutter

Conclusion

showing a toast notification doesn’t require any extra code or a plugin. You can utilize the the ScaffoldMessenger and SnackBar widgets, the Overlay and OverlayEntry widgets, and the AnimatedContainer widget. There are benefits and drawbacks to each method; pick the one that works best for you. Flutter gives you a variety of ways to incorporate toast notifications, a frequent and helpful feature in mobile apps.

Hello, I'm Cakra. I'm currently occupied with developing an application using the Flutter framework. Additionally, I'm also working on writing some articles related to it.

You May Also Like