iOS原生項目中嵌入Flutter

  1. Xcode創(chuàng)建一個Swift項目Swift2FlutterDemo

  2. 使用CocoaPods安裝Flutter SDK

//初始化CocoaPods
pod init
  1. 創(chuàng)建Flutter模塊
flutter create --template module my_flutter
  1. 編寫Podfile文件
#添加模塊所在的路徑
flutter_application_path = './my_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'Swift2FlutterDemo' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Swift2FlutterDemo
  
  #安裝Flutter模塊
  install_all_flutter_pods(flutter_application_path)

end

post_install do |installer|
  flutter_post_install(installer)
end

  1. CocoaPods安裝依賴
pod install
  1. 示例代碼
import UIKit
// 導(dǎo)入Flutter
import Flutter

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    // 創(chuàng)建一個FlutterEngine對象
    lazy var flutterEngine = FlutterEngine(name: "FlutterEngine")
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 啟動FlutterEngine
        flutterEngine.run()
        return true
    }
}
import UIKit
import Flutter

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
        button.backgroundColor = UIColor.red
        button.setTitle("跳轉(zhuǎn)", for: .normal)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        self.view.addSubview(button)
        
        
    }
    
    @objc func buttonClick() {
        
        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
        let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        self.present(flutterViewController, animated: true)
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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