美文网首页
iOS原生项目中嵌入Flutter

iOS原生项目中嵌入Flutter

作者: iOS虞 | 来源:发表于2023-05-08 12:02 被阅读0次
    1. Xcode创建一个Swift项目Swift2FlutterDemo

    2. 使用CocoaPods安装Flutter SDK

    //初始化CocoaPods
    pod init
    
    1. 创建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
    // 导入Flutter
    import Flutter
    
    @main
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        // 创建一个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("跳转", 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)
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS原生项目中嵌入Flutter

          本文链接:https://www.haomeiwen.com/subject/kpclsdtx.html