Flutter和iOS 多入口混编

670 阅读1分钟

第一步:创建一个engineGroup


import UIKit

import Flutter

class FBTool: NSObject {

    static var engineGroup = FlutterEngineGroup(name: "flutter-ios—mixtrue", project: nil)

}

第二步:创建一个FBaseViewController 继承自FlutterViewController

   import UIKit
   import Flutter

    class FBaseViewController: FlutterViewController {
    init(withEntryPoint entryPoint:String?) {
        let newEngine = FBTool.engineGroup.makeEngine(withEntrypoint: entryPoint ?? "", libraryURI: nil)
        super.init(engine: newEngine, nibName: **nil**, bundle: nil)

    }

    required convenience init(coder aDecoder: NSCoder) {

        self.init(withEntryPoint:nil)
    }
}

第三步:配置Flutter文件。配置多个混编加载入口

@pragma('vm:entry-point')
void main() {
  MultiProvider(
    providers: [
      ChangeNotifierProvider<HomeProvider>(create: (context) => HomeProvider()),
    ],
  );
  return runApp(const MyApp());
}

@pragma('vm:entry-point')
void channel() {
  return runApp(const ChannelApp());
}

@pragma('vm:entry-point') 这句代码是防止flutter优化掉。

第四步:回到iOS逐个加载页面 创建对于控制器加载展示flutter界面

主界面:

import Flutter

import UIKit

import ProgressHUD

    class ManiViewController: UIViewController {
    lazy var vc : ViewController = ViewController.init(withEntryPoint: nil)

    override* func viewDidLoad() {

        super.viewDidLoad()

        addChild(vc)

        let loadingView = UIView.init(frame: **self**.view.bounds)

        loadingView.backgroundColor = .black.withAlphaComponent(0.37)

        ProgressHUD.show(icon: .doc)

        vc.splashScreenView = loadingView

        selfview.addSubview(vc.view)

        vc.view.frame = self.view.bounds

        vc.didMove(toParent: self)

        // Do any additional setup after loading the view.

    }
}

channel界面:

import Flutter

import UIKit

import ProgressHUD

class MyViewController: UIViewController {

    lazy var vc : ViewController = ViewController.init(withEntryPoint: "channel")

    override func viewDidLoad() {

        super.viewDidLoad()

        addChild(vc)

        let loadingView = UIView.init(frame: self.view.bounds)

        loadingView.backgroundColor = .black.withAlphaComponent(0.37)

        ProgressHUD.show(icon: .succeed)

        ProgressHUD.animationType = .circleStrokeSpin

        ProgressHUD.colorBackground = .white

        ProgressHUD.colorHUD = .systemBlue

        ProgressHUD.colorAnimation = .systemBlue

        vc.splashScreenView = loadingView

        self.view.addSubview(vc.view)

        vc.view.frame = self.view.bounds

        vc.didMove(toParent: self)

        // Do any additional setup after loading the view.

    }
}

withEntryPoint 此参数传递Flutter入口函数的名字。其中main函数可以传nil。