preface

Flutter does not seem to support a direct call to Android’s Toast. Instead, Flutter has to implement the Toast popover in its own way. (Wouldn’t it be nice to use iOS?)

Implementation effect

Guide package

Go to the file pubspec.yaml and find this code

dependencies:
  Add the library name to the flutter. Align the library name with the flutter, misalignment will cause an error
  flutter:
    sdk: flutter
Copy the code

Add fluttertoast below: ^4.0.1, make sure that the flutter is aligned, the import will fail if the flutter is not aligned.

dependencies:
  Add the library name to the flutter. Align the library name with the flutter, misalignment will cause an error
  flutter:
    sdk: flutter
  fluttertoast: ^ 4.0.1
Copy the code

Then click in the upper right corner of Android Studiopub get

Utility class

Toast is used almost everywhere. Write a Toast utility class to make it easy to call.

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

class ToastUtils {

  static void shotToast(
    String message, [// The square brackets are optional, and the default value is on the right side of the equal sign
    Toast time = Toast.LENGTH_SHORT,
    ToastGravity gravity = ToastGravity.BOTTOM,
    Color backColor = Colors.black45,
    Color textColor = Colors.white,
  ]) {
    Fluttertoast.showToast(
        msg: message,// Message content
        toastLength: time,// Stay time
        gravity: gravity,// The location of the occurrence
        timeInSecForIosWeb: 1,
        backgroundColor: backColor,/ / the background color
        textColor: textColor,/ / the foreground
        fontSize: 16.0);// Text size}}Copy the code

Pop up the Toast

Simply do not be too simple, after the call passed a message content is done, if you want to change the color and time also passed ok

void _clickLogin() {
    if (_user.toString().isEmpty) {
      ToastUtils.shotToast("Please enter your mobile phone number.");/ / pop up the Toast
      return;
    }
    if (_password.toString().isEmpty) {
      ToastUtils.shotToast("Please enter your password");/ / pop up the Toast
      return;
    }
    _doLogin();
  }
Copy the code

Q&A

If the following error is reported during the call

Unhandled Exception: MissingPluginException(No implementation found for method showToast on channel PonnamKarthik/fluttertoast)
Copy the code

Click the Android Studio File->Invalidate Caches/Restart button to clear the cache and Restart it again.