【Flutter 混合开发】添加 Flutter 到 iOS

移动开发 作者: 2024-08-24 20:25:01
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生

创建 Flutter module

cd ios 项目根目录
flutter create --template module my_flutter

将Flutter模块嵌入到现有应用程序中

  • 使用CocoaPods和已安装的Flutter SDK(推荐)。
  • 为Flutter引擎,已编译的Dart代码和所有Flutter插件创建 frameworks。手动嵌入 frameworks,并在Xcode中更新现有应用程序的构建设置。

使用CocoaPods和已安装的Flutter SDK

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

target 'My App' do
 install_all_flutter_pods(flutter_application_path)
end


在Xcode中嵌入 Flutter Frameworks

flutter build ios-framework --output=./Flutter/

创建 FlutterEngine 和 FlutterViewController

import UIKit
import Flutter

@UIApplicationMain
class AppDelegate: FlutterAppDelegate {
  lazy var flutterEngine = FlutterEngine(name: "my flutter engine")

  override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    flutterEngine.run();
    
    return super.application(application,didFinishLaunchingWithOptions: launchOptions);
  }
}
import UIKit
import Flutter

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type:UIButton.ButtonType.custom)
        button.addTarget(self,action: #selector(showFlutter),for: .touchUpInside)
        button.setTitle("显示 Flutter",for: UIControl.State.normal)
        button.frame = CGRect(x: 80.0,y: 210.0,width: 160.0,height: 40.0)
        button.backgroundColor = UIColor.blue
        self.view.addSubview(button)
    }
    
    @objc func showFlutter() {
      let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
      let flutterViewController =
          FlutterViewController(engine: flutterEngine,nibName: nil,bundle: nil)
      present(flutterViewController,animated: true,completion: nil)
    }


}
func showFlutter() {
  let flutterViewController = FlutterViewController(project: nil,bundle: nil)
  present(flutterViewController,completion: nil)
}

指定入口点

flutterEngine.run(withEntrypoint: "newEntrypoint",libraryURI: "main.dart")

初始化路由

let flutterEngine = FlutterEngine()
flutterEngine.run(
  withEntrypoint: FlutterDefaultDartEntrypoint,initialRoute: "/one_page")

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68007.html