Flutter跳轉(zhuǎn)到原生iOS巷送、Android頁面

本文針對初學者, 講述用flutter自帶方法做簡單邏輯跳轉(zhuǎn)處理.
非初學者或想更方便實現(xiàn)功能的驶忌,可了解插件flutter_boost及其它.

  • Flutter跳轉(zhuǎn)到原生iOS頁面

1. flutter頁面中:
class _MyHomePageState extends State<MyHomePage> {

  //平臺通道––––跳轉(zhuǎn)到iOS頁面
  static const platform = const MethodChannel('samples.flutter.jumpto.iOS');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            TextButton(onPressed: _jumpToIosMethod, child: Text('跳轉(zhuǎn)到iOS頁面')),
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }



  //跳轉(zhuǎn)到iOS頁面
  Future<Null> _jumpToIosMethod() async {
    final String result = await platform.invokeMethod('jumpToIosPage');
    print('result===$result');

  }

}
2. iOS的 AppDelegate.swift :
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 //設(shè)置代理 ,配置導航欄的顯示與否
      window?.makeKeyAndVisible()
    
     
      let jumpIosChannel = FlutterMethodChannel(name: "samples.flutter.jumpto.iOS",binaryMessenger: controller.binaryMessenger)
    
   
      //處理-----跳轉(zhuǎn)到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) //跳轉(zhuǎn)頁面
      })
      
      
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    
    //跳轉(zhuǎn)到iOS頁面
    private func jumpToIosPageMethod(result: FlutterResult) {
             
                let vc: UIViewController = JumpTestViewController()
                vc.navigationItem.title = "原生頁面"
               self.navigationController?.pushViewController(vc, animated: true)
      
          result("跳轉(zhuǎn)")
    }
    
    
    //實現(xiàn)UINavigationControllerDelegate代理
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        //如果是Flutter頁面笑跛,導航欄就隱藏
        navigationController.navigationBar.isHidden = viewController.isKind(of: FlutterViewController.self)
    }

}

\color{OrangeRed}{說明}:之所以讓AppDelegate繼承于UINavigationControllerDelegate付魔,并實現(xiàn)navigationController:willShow方法聊品,\color{brown}{是因為flutter頁面跳轉(zhuǎn)到原生頁面返回后,iOS的導航欄并沒有消失}几苍,所以實現(xiàn)代理方法對導航欄的顯示做了判斷翻屈。

JumpTestViewController.swift 為:

import Foundation

class JumpTestViewController: UIViewController {
    
    lazy var testLabel: UILabel = {
        let label = UILabel()
        label.frame.size = CGSize(width: 300, height: 50)
        label.backgroundColor = UIColor.blue
        label.textColor = UIColor.white
        label.text = "原生界面"
        label.textAlignment = .center
        
        label.center.x = self.view.bounds.width/2
        label.center.y = self.view.bounds.height/2
        
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.view.addSubview(testLabel)
    }
    
}
3. 效果展示
iOS.gif
  • Flutter跳轉(zhuǎn)到原生Android頁面

1. flutter頁面中:
class _MyHomePageState extends State<MyHomePage> {

  //平臺通道––––跳轉(zhuǎn)到Android頁面
  static const platform = 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>[

            TextButton(onPressed: _jumpToAndroidMethod, child: Text('跳轉(zhuǎn)到Android頁面')),
          ],
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }


  //跳轉(zhuǎn)到Android頁面
  Future<Null> _jumpToAndroidMethod() async {
    final String result = await platform.invokeMethod('jumpToAndroidPage');
    print('result===$result');

  }
}
2. Android的 MainActivity.kt :
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)

        //跳轉(zhuǎn)到原生Android頁面
        JumpChannel(flutterEngine.dartExecutor.binaryMessenger,this)

    }
}

JumpChannel.kt :

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

    init {
        channel = MethodChannel(flutterEngine, batteryChannelName)
        channel.setMethodCallHandler(this)
        mActivity = activity;
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {

        if (call.method == "jumpToAndroidPage") {

            var  intent = Intent(mActivity,SecondActivity::class.java)
            mActivity.startActivity(intent)

            result.success('跳轉(zhuǎn)');
        }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文件夾下創(chuàng)建一個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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textSize="18sp"
        android:text="安卓原生界面" />
</RelativeLayout>
3. 效果展示
android.gif

Demo:flutter_jumpto_native

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末擦剑,一起剝皮案震驚了整個濱河市妖胀,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌惠勒,老刑警劉巖赚抡,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異纠屋,居然都是意外死亡涂臣,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門售担,熙熙樓的掌柜王于貴愁眉苦臉地迎上來赁遗,“玉大人,你說我怎么就攤上這事族铆⊙宜模” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵哥攘,是天一觀的道長剖煌。 經(jīng)常有香客問我,道長逝淹,這世上最難降的妖魔是什么耕姊? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮栅葡,結(jié)果婚禮上茉兰,老公的妹妹穿的比我還像新娘。我一直安慰自己欣簇,他們只是感情好规脸,可當我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著醉蚁,像睡著了一般燃辖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上网棍,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天黔龟,我揣著相機與錄音,去河邊找鬼。 笑死氏身,一個胖子當著我的面吹牛巍棱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蛋欣,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼航徙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了陷虎?” 一聲冷哼從身側(cè)響起到踏,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎尚猿,沒想到半個月后窝稿,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡凿掂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年伴榔,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片庄萎。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡踪少,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出糠涛,到底是詐尸還是另有隱情援奢,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布忍捡,位于F島的核電站萝究,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏锉罐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一绕娘、第九天 我趴在偏房一處隱蔽的房頂上張望脓规。 院中可真熱鬧,春花似錦险领、人聲如沸侨舆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挨下。三九已至,卻和暖如春脐湾,著一層夾襖步出監(jiān)牢的瞬間臭笆,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留愁铺,地道東北人鹰霍。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像茵乱,于是被迫代替她去往敵國和親茂洒。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容