Flutter calls native methods

There are 3 major steps for Flutter to call native methods:

  1. Call native method in flutter
  2. Implement the called method in Android
  3. Implement the called method in iOS

1. Call the native method in flutter

To call native code in flutter, you need to pass messages through the channel, which is MethodChannel on the flutter side.

Future<bool> testAction1() async {
    // Native channel
    // 创建一个我们自定义的channel。
    const platform = MethodChannel("com.test/testAction1");

    bool result = false;
    try {
      // 用channel发送调用消息到原生端,调用方法是:testAction1
      result = await platform.invokeMethod("testAction1");
    } on PlatformException catch (e) {
      print(e.toString());
    }
    return result;
  }

2. Implement the called method in Android

There is a MainActivity.java file in the Android folder in the flutter project folder, and our Android-side plug-in is registered in MainActivity.

public class FlutterNativePlugin implements MethodChannel.MethodCallHandler {
  public static String CHANNEL = "com.test/testAction1";
  // 注意这里的插件名字要和flutter中的一样
  static MethodChannel channel;
  private Activity activity;
  private FlutterNativePlugin(Activity activity) {
    this.activity = activity;
  }
  
  public static void registerWith(PluginRegistry.Registrar registrar) {
    channel = new MethodChannel(registrar.messenger(), CHANNEL);
    FlutterNativePlugin instance = new FlutterNativePlugin(registrar.activity());
    channel.setMethodCallHandler(instance);
  }
  
  @Override
  public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
    // onMethodCall这个方法是插件的回调,这里我们根据方法名isChinese判断调用的方法,然后实现我们的操作就行了。
    if (methodCall.method.equals("testAction1")) {
      boolean test1 = true;
      result.success(test1);
      // 这里直接返回了true,这里只是个例子,而你应该换成你自己的逻辑。
    } else {
      result.notImplemented();
    }
  }
}

Register in MainActivity.java

public class MainActivity extends FlutterActivity {
  @Override  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);  
    GeneratedPluginRegistrant.registerWith(this);  
    registerCustomPlugin(this); 
  }  
  private void registerCustomPlugin(PluginRegistry registrar) { 
    FlutterNativePlugin.registerWith(registrar.registrarFor(FlutterNativePlugin.CHANNEL)); 
  }
}

3. Implement the called method in iOS

Call the plugin code

import Foundation
import Flutter

class FlutterNativePlugin: NSObject, FlutterPlugin {
    
    static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "com.test/testAction1", binaryMessenger: registrar.messenger())
        let instance = FlutterNativePlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "testAction1" {
            result(true)
        } else {
            result(FlutterMethodNotImplemented)
        }
    }
}

Register code in AppDelegate

override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      FlutterNativePlugin.register(with: self.registrar(forPlugin: "FlutterNativePlugin")!)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

Guess you like

Origin blog.csdn.net/guoxulieying/article/details/131534643