IOS

关注公众号 jb51net

关闭
首页 > 软件编程 > IOS > iOS 项目嵌入Flutter

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

作者:iOS_Apple

这篇文章主要介绍了iOS 项目嵌入Flutter 运行,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一  创建Flutter 模块

命令行

flutter create --template module my_flutter

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

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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文