Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Flutter Toast
3.
Creating Toast Message In Flutter
4.
Creating Custom Toast Message In Flutter
5.
Flutter Toast Properties
5.1.
Msg
5.2.
toastLength
5.3.
Gravity
5.4.
fontSize
5.5.
backgroundColor
5.6.
textColor
6.
Flutter Toast & Custom Toast Example
7.
Frequently Asked Questions
7.1.
Which package to import for the Flutter toast message?
7.2.
What is Flutter?
7.3.
Can we change the color of the toast notification?
7.4.
What is the difference between Snackbars and toasts?
7.5.
What are the advantages of using Flutter?
8.
Conclusion
Last Updated: Mar 27, 2024

Flutter Toast in Flutter

Author Divyansh Jain
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Toast is a flutter flash message that displays information to the user for a limited amount of time. 
Toast Notification Message is yet another term for Flutter Toast. It's a short message that often appears at the bottom of the device's screen by default. It will soon disappear on its own after the developers' time limit has expired. The toast notification was primarily utilized by developers to provide feedback on the user's action.

Flutter Toast

In most cases, a toast message will be used to notify the user of the status of the operation. For example, after completing a registration form, we may send a toast message to the user informing them of the progress of the registration.

There is no unique widget or method for displaying a toast message in flutter. We can replace toast with a snackbar widget, but we can't adjust the location of the snackbar as we can with toast. And, that’s why we must employ the FlutterToast dependency to provide functionality for showing toast messages to our flutter application.

Flutter Toast shows a plain toast with no animations. Consider utilizing Motion toast if you want to provide a stylish and attractively animated toast.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating Toast Message In Flutter

In Android applications, displaying a toast notification message is a must-have feature. We can do that with only a few lines of code. In this part, we'll look at how to use Flutter to construct a toast message. To use toast notification in Flutter, we must first import the fluttertoast package.

Now, we will follow the instructions below to generate and display a toast message in Flutter:

  • Construct a project with Flutter.
  • Add FlutterToast as a project dependency.
  • Include the flutter toast package to your project: - import ‘package:fluttertoast/fluttertoast.dart'
  • Make a call to FlutterToast.ShowToast() function and also provide needed arguments.
     

Step - 1

Now let’s add the FlutterToast dependency to the pubspec.yaml file in our project's root folder.

pubspec.yaml

dependencies:
  fluttertoast: ^8.0.7

Step - 2

To employ toast functionality in our app, import the fluttertoast package.

import ‘package:fluttertoast/fluttertoast.dart’;

Step - 3

Now we'll show a toast message that's been removed from its context. To showcase a toast message FlutterToast. ShowToast() should be called with a string value for the message property. Our message will be this string.

Fluttertoast.showToast(
                msg: "This is a toast message",
              );

Stop!, Wait a Minute!

Do you have android 11 and above? The above technique (FlutterToast.ShowToast()) will function flawlessly on Android devices running version 10 or lower. All properties other than msg and toastLength will not function on smartphones running Android version 11 or above. Consider making custom toast for Android versions 11 and above, as described further down.

Creating Custom Toast Message In Flutter

We'll employ the same dependency (FlutterToast) as before to construct a custom toast message in Flutter. This dependency now includes a new technique to make a toast message using build context. Let's get started with the code now that we've added the library and imported the package.
We must define an object of the FToast class, which is included in the dependency.

FToast fToast;

In the initState() function, we must now initialise the object using the current context.

@override
  void initState() {
    super.initState();
    fToast = FToast();
    fToast.init(context);
  }

It's time to come up with a unique toast message. Let's make a custom toast message using the container widget and apply it to a widget variable.

Custom Toast Widget Code

Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.greenAccent,
      ),
      child: Text("We have made a Custom Toast"),
);

To show the above-created custom toast message, we must add the above widget as a child to fToast.ShowToast() function.

fToast.showToast(
        child: toast,
);

Willy Wonka Reaction GIF

#Giphy 

Flutter Toast Properties

Let's personalize the toast message using FlutterToast.ShowToast() 's various settings. The toast message will be styled and positioned with the aid of these settings.

Msg

It takes a string as input. This will be used to show the user the message.

Fluttertoast.showToast(
                msg: "This is a toast message",
              );

toastLength

It recognises constants of Toast.LENGTH_LONG and Toast.LENGTH_SHORT as significance. We'll apply it to adjust the timeframe the toast message is shown.

Fluttertoast.showToast(
                msg: "This is a toast",
                toastLength: Toast.LENGTH_LONG
              );

Gravity

This attribute will be used to adjust the toast message's location. It takes ToastGravity constants. We'll take advantage of ToastGravity. CENTER. Take a look at the rest for yourself.

Fluttertoast.showToast(
                msg: "Be a Ninja Coder !!",
                toastLength: Toast.LENGTH_LONG,
                gravity: ToastGravity.CENTER
              ); 

fontSize

It takes double as value. This attribute will be used to adjust the font size of the toast message.

Fluttertoast.showToast(
      msg: "Be a Ninja Coder !!",
      toastLength: Toast.LENGTH_LONG,
      fontSize: 20
);

backgroundColor

It uses the colour of the material as a value. This attribute will be used to adjust the toast message's background colour.

Fluttertoast.showToast(
      msg: "Be a Ninja Coder !!",
      toastLength: Toast.LENGTH_LONG,
      fontSize: 20,
      backgroundColor: Colors.green
    );

textColor

This parameter will be used to adjust the toast message's text colour. It uses the colour of the material as a value.

Fluttertoast.showToast(
      msg: "Be a Ninja Coder !!",
      toastLength: Toast.LENGTH_LONG,
      fontSize: 20,
      textColor: Colors.green
    );

Flutter Toast & Custom Toast Example

Let's look at an example of how to use the FlutterToast dependency in flutter to create toast messages and custom toast messages. 

We'll show two raised buttons in this example, one for showing a standard toast message and the other for displaying a personalised toast message. Two methods will be created: showToast() and showCustomToast(). These routines will be called from the onPressed() callbacks of their respective buttons.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
 
void main()
{
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Learning',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(),
    );
  }
}
 
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState()
  {
    return _MyHomePageState();
  }
}
 
class _MyHomePageState extends State<MyHomePage> {
  FToast fToast;
 
  @override
  void initState() {
    super.initState();
    fToast = FToast();
    fToast.init(context);
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Flutter Toast"),
        ),
        body: Container(
          margin: EdgeInsets.all(20),
          alignment: Alignment.topCenter,
          child: Column(
            children: [
              ElevatedButton(
              child: Text("Display Toast"),
                onPressed: () {
                  showToast();
                },
              ),
              ElevatedButton(
                child: Text("Display Custom Toast"),
                onPressed: () {
                  showCustomToast();
                },
              ),
            ],
          ),
        )
    );
  }
 
  void showToast() {
    Fluttertoast.showToast(
      msg: "Be a Ninja Coder !!",
      toastLength: Toast.LENGTH_SHORT,
    );
  }
 
  showCustomToast() {
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.greenAccent,
      ),
      child: Text("A Custom Toast by Ninja Coder !!"), 
    );
 
    fToast.showToast(
        child: toast,
        toastDuration: Duration(seconds: 3),
        );
  }

Output:

On clicking the “Display Toast” button, we will see a toast notification underneath as “Be a Ninja Coder !!”.

And, after clicking on the “Display Custom Toast” button, we will see the Custom toast notification as depicted in the image above.

Hurray! We got the output as we wanted it to be.

Frequently Asked Questions

Which package to import for the Flutter toast message?

After adding the dependency, you have to import the below package to employ toast functionality:- 

import ‘package:fluttertoast/fluttertoast.dart’;

What is Flutter?

Flutter is a cross-platform development framework used to write code and can deploy on various platforms like android, iOS, and desktop.

Can we change the color of the toast notification?

Yes, we can change several properties of the toast notification such as background color, font size, toast duration, gravity, etc. Refer to the above-mentioned flutter toast properties to understand more in brief.

What is the difference between Snackbars and toasts?

Snackbars use a message at the bottom of the screen to offer quick feedback on an action. Snackbars include a single line of text that is directly connected to the action taken. There may be a text action, but there are no icons. Toasts are mostly used for system messages (Android only).

What are the advantages of using Flutter?

Flutter is a potent tool. Following are a few advantages of using Flutter-

  • Faster Development
  • Live and Hot Reloading
  • Good Community
  • Minimal Code
  • Documentation
  • Cross-Platform Development
  • UI Focused

Conclusion

To summarize the article, we have understood what a Flutter toast is and its key properties. Also, we have talked about how to create a flutter toast using the showtoast method and also created a custom toast with certain user-based specifications.

Hope you learned something. But the knowledge never stops, So to learn more you can visit our website for more articles. Check out our articles on Flutter CheckboxFlutter Images, and Flutter Charts.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning Ninja :) 

Previous article
Flutter Webview
Next article
Flutter Progress Bar- Linear and Circular
Live masterclass