Flutter Application to Show Android’s Toast Message

You are currently viewing Flutter Application to Show Android’s Toast Message
Toast Message in Flutter

Android’s Toast Message in Flutter

Flutter application to show Android’s Toast Message.

Screenshot

Methods and code to Show Toast message in flutter.

To show Toast Message in flutter, I’m communicating to native code using Platfrom Channels from flutter, and from native code I’m showing the Toast message.

Platform Channels:

Which is provided by flutter to communicate between native code and flutter code.

Define Channel in Flutter

static const platform = const MethodChannel('flutter.toast.message.channel');

Define Channel/Handler in Android

    MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
          
    }

Define platform channel as above and provide channel name, This Channel name must be same for both platform flutter code and Android Natice Code.

See also  Customizable Animated Toast in Flutter

Create Class in Flutter:

To communicate with Android in order to show Toast message.

    class Toast {
      Toast(String message) {
        _showToast(message);
      }

      static const platform = const MethodChannel('flutter.toast.message.channel');

      Future<Null> _showToast(String message) async {
        // invoke method, provide method name and arguments.
        await platform.invokeMethod('toast', {'message': message});
      }
    }

Handle Method invocation from Flutter in Android:

    class MainActivity : FlutterActivity() {
        companion object {
            const val CHANNEL = "flutter.toast.message.channel"
            const val METHOD_TOAST = "toast"
            const val KEY_MESSAGE = "message"
        }

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            GeneratedPluginRegistrant.registerWith(this)

            // handle method invocation from flutter, and perform action
            MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
                if (call.method == METHOD_TOAST) {
                    val message = call.argument<String>(KEY_MESSAGE)
                    Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

That’s all we need to do to show Android Toast message in flutter.

See also  Hijri Date Picker in Flutter

Usage:

To show toast messages from flutter, Simply call Toast class with your message as argument as below:

    Toast("Hello, I'm Toast from Flutter.");

Learn about toast. click here

Credit

This project is developed by UttamPanchasara
Download this project from the below link.
https://github.com/UttamPanchasara/FlutterToast/archive/refs/heads/master.zip
You can visit the source page from the below link:
https://github.com/UttamPanchasara/FlutterToast

Spread the love

Leave a Reply