Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Android toast notification can use to give quick message to user and It will disappear after a few seconds.
But when It comes to the Flutter there is no any straightforward way to show this toast messages. Therefore, we need to find an alternative approach to implement that. In that case platform channel will be your friend.
Platform channel will allow developers to run platform specific code inside the flutter app. Actually it’s a message passing method. It contain mainly 2 steps
Because of the platform channel we can feel the true power of android and ios inside the flutter app.
First let’s implement dart code and then we can move to the android Side.
We need MethodChannel to create a channel in the Flutter. First, we need to import flutter service package.
import 'package:flutter/services.dart';
Next we need to create a object of MethodChannel class
static const platform = const MethodChannel("toast.flutter.io/toast");
In here we need to pass unique channel name to the constructor. This channel name use to identify each channel uniquely.
Next we need to specify which method need to invoke In Android Side. You can use any method name here. We can called this method when someone click a button.
platform.invokeMethod("showToast");
Next move to the native Android side. For that, we need to open the MainActivity file. In your editor, you can follow this path to open MainActivity file.
android/src/main/java/MainActivity
First, you can create a variable to assign the channel name. In here we need to use the same channel name which we was specified in the flutter code.
private static final String CHANNEL = "toast.flutter.io/toast";
In here we need to create a new MethodChannel Object. As the second parameter of the constructor we need to pass channel name. The method call handler will invoke when we call the method from flutter side using invokeMethod. Inside the onMethodCall we need to check which method. Because we can call multiple method through the single platform channel.
new MethodChannel(getFlutterView(), CHANNEL)
.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("showToast")) {
Toast.makeText(getApplicationContext(), "Flutter Toast", Toast.LENGTH_SHORT).show();
} else {
result.notImplemented();
}
}
});
Then run the app in android simulator and you can see the Toast messages for each click.
If you have any doubt you can get the project from here.