做电影网站用什么主机好,wordpress可视化插件,企业cms wordpress,门户网站系统建设项目投标书在Flutter中#xff0c;Platform Channel允许Flutter与原生平台#xff08;如Android和iOS#xff09;之间进行双向通信#xff0c;以便在Flutter应用程序和原生代码之间传递消息和调用功能。
以下是使用Platform Channel与原生通信的一般步骤#xff1a;
1. 在Flutter端…在Flutter中Platform Channel允许Flutter与原生平台如Android和iOS之间进行双向通信以便在Flutter应用程序和原生代码之间传递消息和调用功能。
以下是使用Platform Channel与原生通信的一般步骤
1. 在Flutter端创建一个MethodChannel对象用于发送消息给原生平台。通常在Flutter Widget的初始化方法中创建MethodChannel。
import package:flutter/services.dart;// 创建MethodChannel对象
MethodChannel _channel MethodChannel(com.example.channelName);2. 在Flutter端发送消息给原生平台可以使用MethodChannel的invokeMethod方法。
// 发送消息给原生平台
dynamic result await _channel.invokeMethod(methodName, arguments);3. 在原生平台如Android和iOS实现对应的方法用于接收Flutter端发送的消息。
对于Android平台可以在MainActivity或Application类中注册MethodChannel并实现对应的方法。
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;public class MainActivity extends FlutterActivity {private static final String CHANNEL com.example.channelName;Overridepublic void configureFlutterEngine(FlutterEngine flutterEngine) {super.configureFlutterEngine(flutterEngine);new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler((call, result) - {if (call.method.equals(methodName)) {// 处理Flutter端发送的消息String arg call.arguments.toString();// 执行相应的操作// ...// 将结果返回给Flutter端result.success(Result from native);} else {result.notImplemented();}});}
}对于iOS平台在AppDelegate.m文件中注册MethodChannel并实现对应的方法。
#import AppDelegate.h
#import GeneratedPluginRegistrant.himplementation AppDelegate- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[GeneratedPluginRegistrant registerWithRegistry:self];FlutterViewController *controller (FlutterViewController *)self.window.rootViewController;FlutterMethodChannel *channel [FlutterMethodChannelmethodChannelWithName:com.example.channelNamebinaryMessenger:controller.binaryMessenger];[channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {if ([methodName isEqualToString:call.method]) {// 处理Flutter端发送的消息NSString *arg call.arguments;// 执行相应的操作// ...// 将结果返回给Flutter端result(Result from native);} else {result(FlutterMethodNotImplemented);}}];return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
通过以上步骤你可以在Flutter端和原生代码之间进行双向通信。
以下是我项目初期的调研代码块
flutter的代码
class GetxStatePage extends StatefulWidget {const GetxStatePage({super.key});overrideStateStatefulWidget createState() {return GetxStatePageState();}
}class GetxStatePageState extends StateGetxStatePage {late MethodChannel _channel;overridevoid initState() {super.initState();//初始化MethodChannel通道名称“multiple-flutters”Android端ios也要统一_channel const MethodChannel(multiple-flutters);}overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(backgroundColor: SGColors.white,title: const Text(Getx,style: TextStyle(color: SGColors.textColor),),),body: Center(child: InkWell(onTap: () {String value Hello from Flutter;//这里定义方法和参数_channel.invokeMethodvoid(nextData, {data: value});// 在此处添加您希望执行的点击事件print(跳转到Android);},child: SizedBox(width: 100,height: 100,child: Text(Getx),),),),),);}
}我们再看看Android端的实现代码首先打通通道需要enginechannel与flutter端的统一就行
class EngineBindings(activity: Activity, delegate: EngineBindingsDelegate, entrypoint: String,initialRoute: String) :DataModelObserver {val channel: MethodChannelval engine: FlutterEngineval delegate: EngineBindingsDelegateinit {// This has to be lazy to avoid creation before the FlutterEngineGroup.val dartEntrypoint DartExecutor.DartEntrypoint(FlutterInjector.instance().flutterLoader().findAppBundlePath(), entrypoint)// engine BaseApplication.getApplication().engines.createAndRunEngine(activity, dartEntrypoint)engine BaseApplication.getApplication().engines.createAndRunEngine(activity, dartEntrypoint, initialRoute)this.delegate delegatechannel MethodChannel(engine.dartExecutor.binaryMessenger, multiple-flutters)}/*** This setups the messaging connections on the platform channel and the DataModel.*/fun attach() {DataModel.instance.addObserver(this)channel.invokeMethod(setCount, DataModel.instance.counter)channel.setMethodCallHandler { call, result -when (call.method) {incrementCount - {DataModel.instance.counter DataModel.instance.counter 1result.success(null)}next - {this.delegate.onNext()result.success(null)}nextData - {val data: String? call.argument(data)this.delegate.onNext(data)result.success(null)}else - {result.notImplemented()}}}}/*** This tears down the messaging connections on the platform channel and the DataModel.*/fun detach() {engine.destroy();DataModel.instance.removeObserver(this)channel.setMethodCallHandler(null)}override fun onCountUpdate(newCount: Int) {channel.invokeMethod(setCount, newCount)}}具体的activity必须继承FlutterActivity且这个类必须在主配置清单AndroidMainfest.xml中配置
activityandroid:name.ui.demo.SingleFlutterActivityandroid:configChangesorientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiModeandroid:exportedtrueandroid:hardwareAcceleratedtrueandroid:windowSoftInputModeadjustResize /class FlutterToAndroidActivity : FlutterActivity(), EngineBindingsDelegate {var mFlutterApi: SGAndroid2Flutter? nullprivate val engineBindings: EngineBindings by lazy {EngineBindings(activity this, delegate this, entrypoint FlutterRouter.MESSAGE_CENTER_ENTRY_POINTER, initialRoute ${FlutterRouter.MESSAGE_CENTER_ROUTER}?psId1234)}override fun onDestroy() {super.onDestroy()engineBindings.detach()}override fun provideFlutterEngine(context: Context): FlutterEngine? {return engineBindings.engine}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)engineBindings.attach()setContentView(layout.activity_flutter_to_android)val extraString intent.getStringExtra(extraString)tv_center.text extraStringval binaryMessenger: BinaryMessenger provideFlutterEngine(this)!!.getDartExecutor().getBinaryMessenger()mFlutterApi SGAndroid2Flutter(binaryMessenger)tv_center.setOnClickListener {callFlutterMethod()}}private fun callFlutterMethod() {val handler Handler(Looper.getMainLooper())(0..2).map { it.toLong() * 100 }.forEach {handler.postDelayed(it) {mFlutterApi?.sendData(it.toString()) { // 必须在主线程中调用println(从 Flutter 获取到的值是$it ) // true回调在主线程}}}}override fun onNext() {}override fun onNext(str: String?) {}
}就可以在onNext的方法中调用我们的操作
/*** flutter 调用原生的方法,原生写法* */override fun onNext(str: String?) {val flutterIntent Intent(this, FlutterToAndroidActivity::class.java)flutterIntent.putExtra(extraString, str)startActivity(flutterIntent)
}最后执行flutter跳转FlutterToAndroidActivity成功flutter成功调用原生Android的方法。
体会
之前一直使用纯flutter开发当需要原生加flutter开发的时候其实成本更大了。
他既需要Android写好桥接代码又需要ios写一套flutter端的是一套。
为什么会这样因为船大难掉头一些大的现有项目没办法短时间改技术栈一些公司会拿出一部分试试水。部分代码迁移。为以后的项目打基础。
遇到些特殊的需求会更麻烦比如我们这种做法需要在原生端获取网络数据去请求接口然后把数据传递给flutter而一开始请求哪个接口传哪些参数又需要flutter传给原生Android和ios两端去实现。
所以在项目中我们用到了pigeon的插件这样就不用写太多的代码通信的过程pigeon会帮你自动生成可以看我下一篇文章实践
https://juejin.cn/post/7270861556031700992