MethodMessage for Flutter hybrid development delivers messages in one direction

  • Analysis of the
  • The Android end
  • The Flutter end

God is not fair, and thus there is wealth and poverty, good and evil, beauty and ugliness, success and failure, happiness and unhappiness. God is fair, it gives you money, often will take away your sincerity and kindness; It gives you maturity, often will take away your youth and innocence; It gives you beauty, often will rob you of wisdom and perseverance; It gives you success, but often takes away your health and happiness.

Preface:

In the previous chapter, we explained that EventChannel is a MethodChannel that the Android end sends one-way messages to the Flutter. This MethodChannel is a one-time communication that has a return value and is often used to send messages to the Android end with the Flutter

First effect:

Rendering (1.1)

Analysis of the

The Android side:

  • There is only one button to jump to the Flutter page
  • Use Toast to receive messages sent by Flutter
  • Return data received from the Flutter end (no return)

The Flutter end:

  • Use the TextField() text box to enter text while sending a message to Android

The Android end

Step 1: Create a MethodChannel

 MethodChannel channel = new MethodChannel(messenger, "MethodChannelPlugin");
Copy the code
  • Parameter 1 :BinaryMessenger Messenger tool for sending messages
  • Parameter 2: The channel name must be the same as the channel name at the Flutter endRendering is 1.5Consistent)

Rendering (1.5)

The second step: through the channel. SetMethodCallHandler (this); A message is sent to the Flutter end and returned

public class MethodChannelPlugin implements MethodCallHandler {

		MethodChannel channel = new MethodChannel(messenger, "MethodChannelPlugin");
        channel.setMethodCallHandler(this);

	@Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {// Process method calls from Dart
            case "send":
                showMessage(call.arguments());
                result.success("MethodChannelPlugin received:" + call.arguments);// Return the result to Dart
                break;
            default: result.notImplemented(); }}}Copy the code

Get the label sent by the Flutter side by overriding the call parameter call.method() in onMethodCall(), andRendering (1.2)The corresponding

Rendering (1.2)



Return a value after receiving the argument successfully with result.success()!

MethodChannelPlugin

/ * * * SZJ 2020/11/27 * CSDN blog: https://blog.csdn.net/weixin_44819566/ * WeChat public: rich * MethodChannelPlugin * on code Method Invocation, one-time communication, commonly used for Dart invocation Native methods such as photo shooting; * /
public class MethodChannelPlugin implements MethodCallHandler {
    private final Activity activity;

    /** * Plugin registration. */
    public static void registerWith(BinaryMessenger messenger, Activity activity) {
        MethodChannel channel = new MethodChannel(messenger, "MethodChannelPlugin");
        MethodChannelPlugin instance = new MethodChannelPlugin(activity);
        channel.setMethodCallHandler(instance);
    }

    private MethodChannelPlugin(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {// Process method calls from Dart
            case "send":
                showMessage(call.arguments());
                result.success("MethodChannelPlugin received:" + call.arguments);// Return the result to Dart
                break;
            default: result.notImplemented(); }}/** * Displays data from Dart **@param arguments
     */
    private void showMessage(String arguments) {
        if (activity instanceofIShowMessage) { ((IShowMessage) activity).onShowMessage(arguments); } Toast.makeText(activity, arguments, Toast.LENGTH_SHORT).show(); }}Copy the code

Register directly in FlutterAppActivity;

BasicMessageChannel communicates with native Android (4.3)

public class FlutterAppActivity extends FlutterActivity implements IShowMessage {

@Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        
       MethodChannelPlugin.registerWith(flutterEngine.getDartExecutor(),this); }}Copy the code

The Flutter end

Step 1: Listen on MethodChannel

  MethodChannel _methodChannel = new MethodChannel("MethodChannelPlugin");
Copy the code

The channel must correspond to the Android side (andRendering (1.6)Corresponding)

Rendering is 1.6

Step 2: Create a TextField and listen for input text

	  TextField(
              onChanged: _onMethodChannelTextChange,
              decoration: InputDecoration(
                hintText: "Using MethodChannel to send natively sent messages",
              ),
            ),
            Text("MethodChannel receives :$_methodMessage")
Copy the code
 void _onMethodChannelTextChange(String value) async {
    var content = await _methodChannel.invokeMethod("send", value);
    print("szjmethodChannel$content");

    setState(() {
      _methodMessage = content ?? "MethodMessage is empty";
    });
  }
Copy the code

Here send and Android correspond to the renderings (1.3)

Rendering (1.3)



Data that corresponds to passing through an identity

Var content = await _methodChannel. InvokeMethod (” send “, value);

Its return value is the data returned by Android, which corresponds to the rendering (1.4)

Rendering (1.4)



Go here and the code for the Flutter side is done

Take a look at the final result:

Final effect:

The complete code

What do you like?

Android jump page, FLutter engine, etc. (4.1)

Pass initialization data to Android for Flutter hybrid development (4.2)

BasicMessageChannel and native android communication (4.3)

Flutter hybrid development EventChannel one-way data transfer (4.4)

How to convert a Flutter project into a Module into an Android project (4.6)

Original is not easy, your thumbs up is my biggest support, leave your thumbs up ~