iOS 项目嵌入Flutter 运行(最新推荐)

一 创建Flutter 模块 命令行 flutter create --template module my_flutter 创建完成后,该模块和普通的Flu

一  创建Flutter 模块

命令行

flutter create --template module my_flutter

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

  • 和之前项目不同的iOS和Android项目是一个隐藏文件,并且我们通常不会单独打开它们再来运行;
  • 它们的作用是将Flutter Module进行编译,之后继承到现有的项目中
my_flutter/
├── .ios/
├── .android/
├── lib/
│   └── main.dart
├── test/
└── pubspec.yaml

二 嵌入到iOS 项目

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

注意my_flutter 的路径对不对

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

三  iOS 项目中调用

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

AppDelegate 中设置代码

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

在ViewControlelr 设置的代码

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

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

到此这篇关于iOS 项目嵌入Flutter 运行的文章就介绍到这了,更多相关iOS 项目嵌入Flutter内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!

您可能有感兴趣的文章
图文详解Flutter单例的如何实现

Flutter中如何使用setState时的6个简单技巧总结

Flutter路由fluro引入配置和如何使用的具体方法

Flutter如何实现下拉刷新和上拉加载更多

封装flutter状态管理工具示例详解