当前位置:   article > 正文

iOS 项目嵌入Flutter 运行_flutter 中 ios 集成flutterviewcontroller

flutter 中 ios 集成flutterviewcontroller

一  创建Flutter 模块

命令行

flutter create --template module my_flutter

创建完成后,该模块和普通的Flutter项目一直,可以通过Android Studio或VSCode打开、开发、运行;

  • 和之前项目不同的iOS和Android项目是一个隐藏文件,并且我们通常不会单独打开它们再来运行;

  • 它们的作用是将Flutter Module进行编译,之后继承到现有的项目中

  1. my_flutter/
  2. ├── .ios/
  3. ├── .android/
  4. ├── lib/
  5. │ └── main.dart
  6. ├── test/
  7. └── pubspec.yaml

二 嵌入到iOS 项目

主要是通过pod 进行设置,之后pod install

注意my_flutter 的路径对不对

  1. platform :ios, '12.0'
  2. # 添加模块所在路径
  3. flutter_application_path = '../my_flutter'
  4. load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
  5. target 'FlutterHybridDemo' do
  6. # Comment the next line if you don't want to use dynamic frameworks
  7. use_frameworks!
  8. # 安装Flutter模块
  9. install_all_flutter_pods(flutter_application_path)
  10. # Pods for FlutterHybridDemo
  11. end
  12. post_install do |installer|
  13. flutter_post_install(installer) if defined?(flutter_post_install)
  14. end

三  iOS 项目中调用

为了在既有的iOS应用中展示Flutter页面,需要启动 Flutter Engine和 FlutterViewController

AppDelegate 中设置代码

  1. import UIKit
  2. import FlutterPluginRegistrant
  3. @main
  4. class AppDelegate: UIResponder, UIApplicationDelegate {
  5. // 1.创建一个FlutterEngine对象
  6. lazy var flutterEngine = FlutterEngine(name:"my flutter engine")
  7. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  8. // Override point for customization after application launch.
  9. // 2 启动
  10. flutterEngine.run()
  11. return true
  12. }

在ViewControlelr 设置的代码

  1. import UIKit
  2. import Flutter
  3. class ViewController: UIViewController {
  4. override func viewDidLoad() {
  5. super.viewDidLoad()
  6. // Do any additional setup after loading the view.
  7. let btn = UIButton(type: UIButton.ButtonType.custom)
  8. btn.setTitle("加载flutter", for: UIControl.State.normal)
  9. btn.frame = CGRect(x: 50, y: 50, width: 200, height: 50)
  10. btn.backgroundColor = UIColor.blue
  11. btn.addTarget(self, action: #selector(showFlutter), for: UIControl.Event.touchUpInside)
  12. view.addSubview(btn)
  13. }
  14. @objc func showFlutter(){
  15. let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
  16. let flutterController = FlutterViewController(engine:flutterEngine, nibName: nil, bundle: nil)
  17. present(flutterController, animated: true)
  18. }
  19. }

显示的结果  顺利加载出flutter 的页面

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/145303
推荐阅读
相关标签
  

闽ICP备14008679号