Flutter application to show Android's Toast Message.
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.
Which is provided by flutter to communicate between native code and flutter code.
static const platform = const MethodChannel('flutter.toast.message.channel');
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.
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});
}
}
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.
To show toast messages from flutter, Simply call Toast class with your message as argument as below:
Toast("Hello, I'm Toast from Flutter.");
If you found this Example helpful, consider buying me a cup of ☕