一、flutter调用原生方法
1.调用android
flutter端
class _MyHomePageState extends State<MyHomePage> { static const MethodChannel methodChannel = MethodChannel("channel_test"); // @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: RaisedButton( child: Text("a"), onPressed: () { () async { String str = await methodChannel.invokeMethod('getRes'); print(str); }(); }, ), ), ); } }
调用android端
package com.rockcheck.flutter_app1; import android.os.Bundle; import androidx.annotation.Nullable; import io.flutter.embedding.android.FlutterActivity; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(getFlutterEngine()); new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(),"channel_test").setMethodCallHandler( (call, result) -> { if (call.method.equals("getRes")) { result.success("aaa"); } else { result.notImplemented(); } } ); } }
2调用ios
flutter端
class _MyHomePageState extends State<MyHomePage> { static const MethodChannel methodChannel = MethodChannel("channel_test"); // @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: RaisedButton( child: Text("a"), onPressed: () { () async { await methodChannel.invokeMethod('set', 'bbb'); String str = await methodChannel.invokeMethod('get'); print(str); }(); }, ), ), ); } }
ios端
@UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) let controller:FlutterViewController = window.rootViewController as! FlutterViewController let userdefault = FlutterMethodChannel(name: "channel_test", binaryMessenger: controller.binaryMessenger) userdefault.setMethodCallHandler { (call, result) in //赋值给了ios端 if "set" == call.method{ self.setPlatString(result: result, str: call.arguments as! String) } //回传给了flutter else if "get" == call.method{ self.getPlatString(result: result) } else{ result(FlutterMethodNotImplemented) } } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } fileprivate func getPlatString(result:FlutterResult){ let token:String = UserDefaults.standard.value(forKey: "v") as! String result(token) } fileprivate func setPlatString(result:FlutterResult,str:String){ UserDefaults.standard.set(str, forKey: "v") UserDefaults.standard.synchronize() result(NSNumber(booleanLiteral: true)) } }