开发者

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

开发者 https://www.devze.com 2023-03-30 10:17 出处:网络 作者: iOS_Apple
目录一  创建Flutter 模块二 嵌入到IOS 项目三  iOS 项目中调用一  创建Flutter 模块
目录
  • 一  创建Flutter 模块
  • 二 嵌入到IOS 项目
  • 三  iOS 项目中调用

一  创建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 项目嵌入Flutter 运行(最新推荐)

二 嵌入到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, didFinishLauncwww.devze.comhingWithOptions 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
        btnandroid.addTarget(self, action: #selector(showFlutter), for: UIControl.E编程客栈vent.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 运行的文章就介绍到这了,更多相关iO编程客栈S 项目嵌入Flutter内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号