欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

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

来源: 开发者 投稿于  被查看 18952 次 评论:69

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 项目

主要是通过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内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • ios开发Flutter构建todo list应用
  • Flutter Module添加到iOS项目示例详解
  • Flutter iOS开发OC混编Swift动态库和静态库问题填坑
  • ios开发Flutter之数据存储
  • Flutter项目在 iOS14 启动崩溃的解决方法
  • Flutter集成到已有iOS工程的方法步骤
  • Flutter调用Android和iOS原生代码的方法示例

用户评论