iOS集成Flutter模块

本文主要介绍原生 iOS 应用如何集成 Flutter 模块。

安装 Flutter

Flutter 支持 macOSWindowsLinux

安装步骤可见官网:https://flutter.dev/docs/get-started/install

(注:本教程使用的是 macOS 系统)

iOS 集成 Flutter 模块

通过 Xcode 创建一个 iOS 原生项目,命名为 Example-Flutter

  1. 通过终端进入 Example-Flutter 当前目录下。
  2. 通过如下命令来创建 Flutter 模块。
flutter create --template module my_flutter

将会生成一个 my_flutter 新目录,结构如下:

my_flutter/
├─.ios/
│ ├─Runner.xcworkspace
│ └─Flutter/podhelper.rb
├─lib/
│ └─main.dart
├─test/
└─pubspec.yaml
  1. 通过 CocoaPods 集成 Flutter 模块。

Example-Flutter 项目目录下创建 Podfile 文件,内容编辑如下:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

flutter_application_path = './my_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'Example-Flutter' do
    install_all_flutter_pods(flutter_application_path)
end

然后,通过 pod install 命令集成 Flutter 模块到 iOS 工程项目中。

输出类似如下日志:

$ pod install
Analyzing dependencies
Downloading dependencies
Installing Flutter (1.0.0)
Installing FlutterPluginRegistrant (0.0.1)
Installing my_flutter (0.0.1)
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `Example-Flutter.xcworkspace` for this project from now on.
Pod installation complete! There are 3 dependencies from the Podfile and 3 total pods installed.

此时,整个项目的目录结构类似是这样的。

some/path/Example-Flutter
├── Example-Flutter/
├── Example-Flutter.xcodeproj
├── Example-Flutter.xcworkspace
├── my_flutter/
│   └── .ios/
│       └── Flutter/
│         └── podhelper.rb
├── Podfile
├── Podfile.lock
└── Pods/
  1. 添加 Flutter 相关代码

修改 AppDelegate.swift 文件。

import FlutterPluginRegistrant
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.
    flutterEngine.run()
    GeneratedPluginRegistrant.register(with: self.flutterEngine);

    return true
}

然后在 iOS 原生页面上添加相应代码。

导入 Flutter package。

import Flutter

增加一个触发按钮,代码如下:

let button = UIButton(type:UIButton.ButtonType.custom)
button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
button.setTitle("Show Flutter!", for: UIControl.State.normal)
button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
button.backgroundColor = UIColor.blue
self.view.addSubview(button)

响应 Button 点击事件,代码如下:

@objc func showFlutter() {
  let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
  let flutterViewController =
      FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
  present(flutterViewController, animated: true, completion: nil)
}

运行效果

  • iOS 原生页面

  • 点击按钮后,显示 Flutter 页面效果。

示例代码

GitHub: iOS-Examples/Example-Flutter