Flutter與Native混合開發-FlutterBoost整合應用和開發實踐(iOS)

Miaoz??發表於2020-07-22

借圖Flutter_Boost

背景:

現在Flutter火熱,各個公司都會嘗試使用Flutter開發,一般採用的都會是混合形式的開發,混合開發目前Flutter官方提供的不太完善、iOS和Android有差異性、介面也不同意、很麻煩,也有一些大廠為了實現高效率高可用自己實現一套混合開發技術,比如閒魚的flutter_boost和哈羅的flutter_thrio。兩者之間優缺點及設計原理、架構等後續再來分析。接下我們先說下flutter_boost在iOS專案中的接入混合實踐。

準備工作:

1.Flutter SDK

為了便於後續我們flutter sdk版本的快速切換,我們需要安裝管理工具,方便我們在後續開發或者除錯過程中快速切換版本。

這裡推薦使用的Flutter SDK管理工具fvm,能快速切換版本,具體不做介紹,直接去檢視文件就可以,很詳細。

安裝自己所需的flutter sdk版本(我這裡安裝的是1.17.1版本,因為需要跟下邊的flutter_boost版本對應):

WX20200719-181209@2x.png

複製程式碼

2.flutter_boost框架

瞭解混合框架flutter_boost,首先需要知道我們需要使用他們的那個版本及版本對應的flutter sdk版本,比如:flutter_boost:v1.17.1-hotfixes 對應的flutter sdk:1.17.1 。

複製程式碼

正式接入:

一、flutter_module工程

1.建立空資料夾後,使用命令:
flutter create -t module flutter_module
複製程式碼

如果iOS使用的是Swift開發使用命令:

flutter create -i swift -t module flutter_module
複製程式碼
2.flutter_module建立完成後,開啟flutter_module資料夾下pubspec.yaml檔案。如下:

pubspec.yaml

注意:這裡我用的flutter_boost的SDK最新版本:v1.17.1-hotfixes
3.cd到flutter_module資料夾下,執行命令:
flutter packages get
複製程式碼

包下載完成後flutter_module工程基本配置已經完成。

二、iOS原生工程

1.建立iOS專案

注意:iOS工程根目錄與flutter_module根目錄平級。

2.cd到iOS工程目錄下建立Podfile檔案,執行命令:

touch Podfile 生成檔案,然後可以使用vim Podfile 編輯或者直接open Podfile 或者直接開啟文字編輯也可以。 在檔案中新增

flutter_application_path = '../flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
install_all_flutter_pods(flutter_application_path)

複製程式碼

pod

3.執行 pod install下載依賴庫。

pod

4.配置專案

如果是OC工程,則不會要做什麼額外處理,如果是Swift專案需要建個橋接檔案FlutterHybridiOS-Bridging-Header.h,同時Build Sttings中需要配置該檔案路徑。

swift呼叫OC橋接檔案

對應路徑

注意:

(1).看其他部落格出現過,檢視Build Phases中是否存在Flutter Build Script的指令碼,如果不存在需要新增對應指令碼,但是目前我沒出現缺失的情況。

生成的Flutter Build Script

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed
複製程式碼

三.程式碼接入實踐

這塊可以直接下載flutter_boost官方例子OCflutter_boost官方例子Swift檢視具體實踐,其中OC例子是最全的,這裡只已Swift專案為基礎介紹基礎使用。

<1>.iOS平臺
  • 1.建立實現flutter_boost路由類,實現FLBPlatform中的協議,和Flutter中也會有對應的方法來處理跳轉操作。(直接參考上邊官方的程式碼類就行),即push模式跳轉、present模式跳轉、關閉頁面等方法。

import Foundation
//import flutter_boost

class PlatformRouterImp: NSObject, FLBPlatform {
   func open(_ url: String, urlParams: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
       //跳轉開啟原生Native頁面
       if (url == "native") {
          self.openNativeVC(url, urlParams: urlParams, exts: exts)
          return
       }

       var animated = false;
       if exts["animated"] != nil{
           animated = exts["animated"] as! Bool;
       }
       let vc = FLBFlutterViewContainer.init();
       vc.setName(url, params: urlParams);
       self.navigationController().pushViewController(vc, animated: animated);
       completion(true);
   }
   
   func present(_ url: String, urlParams: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
       var animated = false;
       if exts["animated"] != nil{
           animated = exts["animated"] as! Bool;
       }
       let vc = FLBFlutterViewContainer.init();
       vc.setName(url, params: urlParams);
       navigationController().present(vc, animated: animated) {
           completion(true);
       };
   }
   
   func close(_ uid: String, result: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
       var animated = false;
       if exts["animated"] != nil{
           animated = exts["animated"] as! Bool;
       }
       let presentedVC = self.navigationController().presentedViewController;
       let vc = presentedVC as? FLBFlutterViewContainer;
       if vc?.uniqueIDString() == uid {
           vc?.dismiss(animated: animated, completion: {
               completion(true);
           });
       }else{
           self.navigationController().popViewController(animated: animated);
       }
   }
   
private func openNativeVC(
       _ name: String?,
       urlParams params: [AnyHashable : Any]?,
       exts: [AnyHashable : Any]?
   ) {
       let vc = UIViewController()
       let animated = (exts?["animated"] as? NSNumber)?.boolValue ?? false
       if (params?["present"] as? NSNumber)?.boolValue ?? false {
           self.navigationController().present(vc, animated: animated) {}
       } else {
     
           self.navigationController().pushViewController(vc, animated: animated)
       }
   }

   func navigationController() -> UINavigationController {
       let delegate = UIApplication.shared.delegate as! AppDelegate
       let navigationController = delegate.window?.rootViewController as! UINavigationController
       return navigationController;
   }
}

複製程式碼
  • 2.flutter_boost初始化,即在啟動的時候初始化框架程式碼。
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

   override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
          //路由建立
          let router = PlatformRouterImp.init();
          //FlutterBoost初始化
           FlutterBoostPlugin.sharedInstance().startFlutter(with: router, onStart: { (engine) in
            
           });
           
           self.window = UIWindow.init(frame: UIScreen.main.bounds)
           let viewController = ViewController.init()
           let navi = UINavigationController.init(rootViewController: viewController)
           self.window.rootViewController = navi
           self.window.makeKeyAndVisible()
           
        return true
    }

複製程式碼
  • 3.具體使用(建立自己的ViewController,新增兩個按鈕進行測試跳轉Native)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        let btn = UIButton(type: .custom);
        btn.backgroundColor = UIColor.red
        btn.frame = CGRect(x: 10, y: 60, width: 60, height: 40)
        btn.setTitle("Push Flutter Page", for: .normal)
        self.view.addSubview(btn);
        btn.addTarget(self, action: #selector(onClickPushFlutterPage), for: .touchUpInside);
        
        let btn2 = UIButton(type: .custom);
        btn2.backgroundColor = UIColor.blue
        btn2.frame = CGRect(x: 10, y: 120, width: 60, height: 40)
        self.view.addSubview(btn2);
        btn2.setTitle("Present Flutter Page", for: .normal)
        btn2.addTarget(self, action: #selector(onClickPresentFlutterPage), for: .touchUpInside);

    }


    @objc func onClickPushFlutterPage(_ sender: UIButton, forEvent event: UIEvent){
//        self.navigationController?.navigationBar.isHidden = true
        //其中這裡的first,在Flutter也會對應初始化的時候註冊該標識對應的Widget。
         FlutterBoostPlugin.open("first", urlParams:[kPageCallBackId:"MycallbackId#1"], exts: ["animated":true], onPageFinished: { (_ result:Any?) in
             print(String(format:"call me when page finished, and your result is:%@", result as! CVarArg));
         }) { (f:Bool) in
             print(String(format:"page is opened\(f)"));
         }
     }
    @objc func onClickPresentFlutterPage(_ sender: UIButton, forEvent event: UIEvent){
         FlutterBoostPlugin.present("second", urlParams:[kPageCallBackId:"MycallbackId#2"], exts: ["animated":true], onPageFinished: { (_ result:Any?) in
             print(String(format:"call me when page finished, and your result is:%@", result as! CVarArg));
         }) { (f:Bool) in
             print(String(format:"page is presented"));
         }
     }
}

複製程式碼

注意點:

(1).呼叫FlutterBoostPlugin.open和present方法時候,傳遞的urlname(first、second)會在Flutter中註冊對應的Widget。

<2>.Flutter平臺
  • 1.main.dart (可以理解為入口類,類似iOS中的Appdelete類),實現Flutter_boost初始化和註冊Native對應的widget。

(1)初始化flutter_boost外掛及註冊對應的widgets。

(2)初始化路由router。

import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'simple_page_widgets.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();

//(1)初始化註冊
    FlutterBoost.singleton.registerPageBuilders(<String, PageBuilder>{
      'first': (String pageName, Map<String, dynamic> params, String _) => FirstRouteWidget(),
      'firstFirst': (String pageName, Map<String, dynamic> params, String _) =>
          FirstFirstRouteWidget(),
      'second': (String pageName, Map<String, dynamic> params, String _) => SecondRouteWidget(),
      'secondStateful': (String pageName, Map<String, dynamic> params, String _) =>
          SecondStatefulRouteWidget(),
    });
    
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Boost example',
        //(2)初始化路由
        builder: FlutterBoost.init(postPush: _onRoutePushed),
        home: Container(color: Colors.white));
  }

//(2)
  void _onRoutePushed(
    String pageName,
    String uniqueId,
    Map<String, dynamic> params,
    Route<dynamic> route,
    Future<dynamic> _,
  ) {}
}
複製程式碼

注意點:

(1)import 'simple_page_widgets.dart'這個dart類中是實現了很多widget,比如first對應的FirstRouteWidget,second對應的SecondRouteWidget等。但是在實際開發中不要把widget放到一個Dart類種實現,降低程式碼冗餘、程式碼複雜度、降低維護成本等。

  • 2.實現widget(具體可以檢視官方類中的simple_page_widgets.dart) 下邊只展示我們之前對應的first和second。
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_module/platform_view.dart'; //封裝的view


/// *********************** FirstRouteWidget*/
class FirstRouteWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FirstRouteWidgetState();
}

class _FirstRouteWidgetState extends State<FirstRouteWidget> {
  _FirstRouteWidgetState();

  // flutter 側MethodChannel配置,channel name需要和native側一致
// static const MethodChannel _methodChannel = MethodChannel('flutter_native_channel');
  // String _systemVersion = '';

  // Future<dynamic> _getPlatformVersion() async {

  //   try {
  //     final String result = await _methodChannel.invokeMethod('getPlatformVersion');
  //     print('getPlatformVersion:' + result);
  //     setState(() {
  //       _systemVersion = result;
  //     });
  //   } on PlatformException catch (e) {
  //     print(e.message);
  //   }

  // }

  @override
  void initState() {
    print('initState');
    super.initState();
  }

  @override
  void didChangeDependencies() {
    print('didChangeDependencies');
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(FirstRouteWidget oldWidget) {
    print('didUpdateWidget');
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    print('deactivate');
    super.deactivate();
  }

  @override
  void dispose() {
    print('[XDEBUG] - FirstRouteWidget is disposing~');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('First Route')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: const Text('Open native page'),
              onPressed: () {
                print('open natve page!');
                FlutterBoost.singleton
                    .open('native')
                    .then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve native route result $value');
                });
              },
            ),
            RaisedButton(
              child: const Text('Open FF route'),
              onPressed: () {
                print('open FF page!');
                FlutterBoost.singleton
                    .open('firstFirst')
                    .then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve FF route result $value');
                });
              },
            ),
            RaisedButton(
              child: const Text('Open second route1'),
              onPressed: () {
                print('open second page!');
                FlutterBoost.singleton
                    .open('second')
                    .then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve second route result $value');
                });
              },
            ),
            RaisedButton(
              child: const Text('Present second stateful route'),
              onPressed: () {
                print('Present second stateful page!');
                FlutterBoost.singleton.open('secondStateful',
                    urlParams: <String, dynamic>{
                      'present': true
                    }).then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve second stateful route result $value');
                });
              },
            ),
            RaisedButton(
              child: const Text('Present second route'),
              onPressed: () {
                print('Present second page!');
                FlutterBoost.singleton.open('second',
                    urlParams: <String, dynamic>{
                      'present': true
                    }).then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve second route result $value');
                });
              },
            ),
            RaisedButton(
              child: Text('Get system version by method channel:' + _systemVersion),
              onPressed: () => _getPlatformVersion(),
            ),
          ],
        ),
      ),
    );
  }
}

/// *********************** SecondRouteWidget*/
class SecondRouteWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Second Route')),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Navigate back to first route when tapped.
            final BoostContainerSettings settings =
                BoostContainer.of(context).settings;
            FlutterBoost.singleton.close(
              settings.uniqueId,
              result: <String, dynamic>{'result': 'data from second'},
            );
          },
          child: const Text('Go back with result!'),
        ),
      ),
    );
  }
}

複製程式碼

注意點:

(1).狀態管理的處理,如果細心地同學會發現,上邊FirstRouteWidget和SecondRouteWidget的繼承類不同,一個是StatelessWidget(非動態的)、StatefulWidget(動態的)兩種狀態管理。具體理解可以自己去查資料學習,後續也會專門講下這個。

場景:

1.原生-->>原生

這個不多說直接跳轉就行

2.原生-->>Flutter

呼叫PlatformRouterImp中的方法

3.Flutter-->>原生

需要Flutter程式碼執行

 FlutterBoost.singleton
                    .open('native')
                    .then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve native route result $value');
                });
複製程式碼

4.Flutter-->>Flutter (走Native原生Controller容器跳轉)

 FlutterBoost.singleton
                    .open('firstFirst')
                    .then((Map<dynamic, dynamic> value) {
                  print(
                      'call me when page is finished. did recieve FF route result $value');
                });
複製程式碼

5.Flutter-->>Flutter(走Flutter自己的Flutter Navigator跳轉)

 Navigator.push<dynamic>(
                    context,
                    MaterialPageRoute<dynamic>(builder: (_) => PushWidget()),
                  );
複製程式碼

這個自己去做處理,建議既然使用flutter_boost就都採用flutter_boost統一的路有跳轉。 如果想實現只開啟一個Flutter的原生控制器,其他走flutter內部跳轉router邏輯,則需要自己處理,或者也可以看下flutter_thrio框架

到這裡基本上全部工作都可以了,Flutter和iOS都會關聯上。直接執行Xcode就可以了。

關於分離開發:

需要注意的地方如果之後考慮分開開發,Flutter同學只開發Flutter的話,需要在flutter_module/.ios/下工程配置之前iOS端的東西即可,就可以使用flutter run直接跑起來,且也能使用flutter_boost路由。做到Flutter開發Flutter,原生開發原生。做到分離。

下一篇會寫下Flutter_Boost在Android中的整合和實踐。

萌圖鎮樓

相關文章