背景
- 在当前前端互联网圈越来越热衷于跨平台技术,这可以有效的为公司降低开发的人力成本,而flutter由于Google的原因,受到了世界范围的青睐,尤其是目前的东方大国资本市场
- 在前面我们了解了flutter的开发环境配置,以及flutter的基本语法,那么在实战项目中应该怎么应用呢?
- 作为一个移动端开发工程师,我们要了解flutter,那我们也需要知道,我们目前的iOS/Android项目工程(iOS无论OC还是Swift,或者Android,只是语法的区别),iOS/Android
项目工程如何混编Flutter呢?
Flutter页面跳转原生页面又是怎么实现的呢?
Flutter页面跳转原生页面
flutter要想跳转到原生页面:
- 首先,需要flutter与原生端协定一个StandardMethodCodec(跳转标准标识),并注册到MethodChannel,(eg:samples.flutter.jumpto.iOS或者 samples.flutter.jumpto.android)
- 然后,使用flutter与原生端协定的参数,调用invokeMthod通道传输指定的参数方法。(eg:jumpToIosPage 或者 jumpToAndroidPage)
MethodChannel
class MainPageState extends State<MyHomePage> {
//–跳转到iOS页面
static const platform2 = const MethodChannel('samples.flutter.jumpto.iOS');
//–跳转到Android页面
static const platform3 = const MethodChannel('samples.flutter.jumpto.android');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20,),
TextButton(onPressed: jumpToIosMethod, child: Text('跳转到iOS页面')),
TextButton(onPressed: jumpToAndroidMethod, child: Text('跳转到Android页面')),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
invokeMethod
//跳转到iOS页面
Future<Null> jumpToIosMethod() async {
final String result = await platform2.invokeMethod('jumpToIosPage');
print('result==$result');
}
//跳转到Android页面
Future<Null> jumpToAndroidMethod() async {
final String result = await platform3.invokeMethod('jumpToAndroidPage');
print('result==$result');
}
iOS调用Flutter跳转原生
- 以Swift为例
- 首先,需要在工程的AppDelegate.swift文件里面导入Flutter框架
import Flutter
- 然后,在核心入口方法didFinishLaunchingWithOptions里面添加与Flutter约定的MethodChannel跳转标识
- 最后,通过setMethodCallHandler判断invoked的方法标识执行页面跳转
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, UINavigationControllerDelegate{
var navigationController: UINavigationController?
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
self.navigationController = UINavigationController.init(rootViewController: controller)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = self.navigationController
self.navigationController?.delegate=self
window?.makeKeyAndVisible()
let jumpIosChannel = FlutterMethodChannel(name: "samples.flutter.jumpto.iOS",binaryMessenger: controller.binaryMessenger)
//处理-----跳转到iOS页面
jumpIosChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
// Note: this method is invoked on the UI thread.
guard call.method == "jumpToIosPage" else {
result(FlutterMethodNotImplemented)
return
}
self?.jumpToIosPageMethod(result: result) //跳转页面
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
//跳转到iOS页面
private func jumpToIosPageMethod(result: FlutterResult) {
let vc: UIViewController = JumpTestViewController()
vc.navigationItem.title = "原生Page"
self.navigationController?.pushViewController(vc, animated: true)
result("跳转")
}
//实现UINavigationControllerDelegate代理
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
//如果是Flutter页面,导航栏就隐藏
navigationController.navigationBar.isHidden = viewController.isKind(of: FlutterViewController.self)
}
}
Android调用Flutter跳转原生
- Android的MainActivity.kt 里面import flutter相关的头文件
package com.example.flutter_jumpto_native
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
//跳转到原生Android页面,为JumpChannel.kt文件里JumpChannel类方法
JumpChannel(flutterEngine.dartExecutor.binaryMessenger,this)
}
}
- Android的JumpChannel.kt文件里面import flutter相关的头文件,
- 然后,里面添加与Flutter约定的MethodChannel跳转标识
- 最后,通过setMethodCallHandler重写onMethodCall判断invoked的方法标识,并执行页面跳转
package com.example.flutter_jumpto_native
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class JumpChannel(flutterEngine: BinaryMessenger, activity: FlutterActivity): MethodChannel.MethodCallHandler {
private val batteryChannelName = "samples.flutter.jumpto.android"
private var channel: MethodChannel
private var mActivity: FlutterActivity
companion object {
private const val TAG = "JumpChannel"
}
init {
Log.d(TAG, "init")
channel = MethodChannel(flutterEngine, batteryChannelName)
channel.setMethodCallHandler(this)
mActivity = activity;
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
Log.d(TAG, "onMethodCall: " + call.method)
if (call.method == "jumpToAndroidPage") {
var intent = Intent(mActivity,SecondActivity::class.java)
mActivity.startActivity(intent)
result.success(TAG);
}else if(call.method == "别的method"){
//处理samples.flutter.jumpto.android下别的method方法
} else {
result.notImplemented()
}
}
}
- SecondActivity.kt :
package com.example.flutter_jumpto_native
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.FragmentActivity
class SecondActivity: FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.e("YM", "第二个页面的渲染");
setContentView(R.layout.activity_second);
}
}
- 在AndroidManifest.xml的application中注册SecondActivity:
<activity android:name=".SecondActivity"/>
- 在res文件夹下layout文件夹的activity_second.xml文件(如果没有就创建一个layout文件夹,并添加activity_second.xml文件)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="安卓-原生界面" />
</RelativeLayout>
原生页面跳转Flutter页面
iOS原生跳转Flutter
- 我们将在应用启动的 app delegate 中创建一个 FlutterEngine,并作为属性暴露给外界。
import UIKit
import Flutter
import FlutterPluginRegistrant
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
flutterEngine.run()
GeneratedPluginRegistrant.register(with: self.flutterEngine)
return true
}
}
- ViewController控制器中添加import Flutter依赖,并调用flutter方法:
import UIKit
import Flutter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.brown
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//搜索到了很多中获取控制器跳转的方法,感觉这种获取 控制器跳转最为流畅 (自我感觉)
let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
present(flutterViewController, animated: true, completion: nil)
}
}
总结
- Flutter与原生混编,核心点就是:
- 首先,两端约定好通道标识,methodChannel
- 然后,两端约定好通道下的跳转页面标识,invokeMethod
- 最后,就是处理数据传输,数据的序列化与反序列化。