Flutter嵌套iOS原生项目(2023年)

276 阅读1分钟

前言:建议创建Flutter项目时候直接使用命令行,不用Android Studio等第三方工具创建,否则会出现项目创建卡顿,或者pod install 各种失败


  • 1.新建一个公有文件夹 flutter 混合开发 ,用来放Flutter项目和iOS项目

image.png

  • 2.cd到flutter 混合开发该目录,执行创建flutter模块,终端执行flutter create --template module my_flutter

  • 3.新建iOS原生项目为 Demo ,一并放到flutter 混合开发,目录结构如下:

image.png

  • 4.cd到iOS目录,分别执行以下命令

pod init
pod install

打开 podfile文件,配置如下图三部分命令

flutter_application_path = '../my_flutter' #这是你本地flutter目录的路径
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
install_all_flutter_pods(flutter_application_path)
#新增的配置
post_install do |installer|
  flutter_post_install(installer) if defined?(flutter_post_install)
end

image.png 请注意查看路径./my_flutter
./../ 这个是linux命令
./代表当前目录
../代表目录下级

以上配置完成后,cd到iOS项目目录,再次执行 pod install

image.png

  • 5.原生代码配置

    为了在既有的iOS应用中展示Flutter页面,需要启动 Flutter Engine和 FlutterViewController。 通常建议为我们的应用预热一个 长时间存活 的FlutterEngine: 我们将在应用启动的 app delegate 中创建一个 FlutterEngine,并作为属性暴露给外界。

  • Swift篇:

import UIKit  
import FlutterPluginRegistrant  
  
@UIApplicationMain  
class AppDelegateUIResponderUIApplicationDelegate {  
   // 1.创建一个FlutterEngine对象  
    lazy var flutterEngine = FlutterEngine(name: "my flutter engine")  
      
    func application(_ applicationUIApplicationdidFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKeyAny]?) -> Bool {  
       // 2.启动flutterEngine  
        flutterEngine.run()  
        return true  
    }  
}
  • Object-C篇:
  • AppDelegate.h代码:
@import UIKit;  
@import Flutter;  
  
@interface AppDelegate : FlutterAppDelegate   
@property (nonatomic,strong) FlutterEngine *flutterEngine;  
@end
  • AppDelegate.m代码:
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Used to connect plugins.  
  
#import "AppDelegate.h"  
  
@implementation AppDelegate  
  
- (BOOL)application:(UIApplication *)application  
    didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKeyid> *)launchOptions {  
        
  self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];  
  [self.flutterEngine run];  
        
  [GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];  
  return [super application:application didFinishLaunchingWithOptions:launchOptions];  
}  
  
@end