Sub topic 5
Integrating the module into an iOS app
This chapter assumes you have a Flutter module from the earlier chapter (created with flutter create --template module), Xcode installed, and CocoaPods available (pod --version prints a version). You also need a native iOS app in Swift or Objective-C. The hosting model of one FlutterEngine plus a FlutterViewController is covered in the engine and view chapter, so here we focus on wiring it into Xcode.
Three ways to bring the module in
Flutter documents three integration routes for iOS. They differ in what the native app depends on at build time.
| Option | What the host links | Flutter SDK needed on build machine | Typical use |
|---|---|---|---|
| CocoaPods | The module source, built as part of your Xcode build | Yes | Small teams, one repository layout, fast iteration |
| Frameworks (`flutter build ios-framework`) | Prebuilt `.xcframework` files | Only on the machine that builds them | Native teams that don't install Flutter |
| Xcode project edits (manual) | Frameworks with hand-edited build settings | Depends | Rarely needed, hard to maintain |
This chapter walks through the CocoaPods route, because it gives you hot reload and a single build command. The frameworks route is covered in the packaging chapter.
How CocoaPods integration fits together
Your host's Podfile loads a Ruby script named podhelper.rb. The module generates that script in its hidden .ios folder. The script adds the Flutter engine, the compiled Dart code, and every plugin the module depends on as pods of your host target.
Step 1: Generate the module's iOS files
The .ios folder is created when the module resolves its dependencies. Run this next to your native project, not inside it:
cd my_flutter_module
flutter pub getThe folder is generated output. Don't edit it by hand, and expect it to be rewritten whenever you change pubspec.yaml. Many teams add .ios/ to .gitignore for the module and regenerate it in CI.
Step 2: Edit the host Podfile
If your host does not have a Podfile yet, run pod init in the Xcode project folder. Then add the module's path and the helper:
platform :ios, '13.0'
flutter_application_path = '../my_flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'MyApp' do
install_all_flutter_pods(flutter_application_path)
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
endPoints to check:
flutter_application_pathis relative to the Podfile. A wrong path produces a "no such file" error whenpod installloads the helper.install_all_flutter_podsgoes inside each host target that shows Flutter. A unit-test target does not need it unless it imports Flutter.flutter_post_installapplies build settings to the pods. Without it you can get architecture or deployment-target warnings that turn into errors.- The
platformline must be at least the minimum iOS version Flutter supports. A lower value fails atpod install.
Now install:
cd MyApp
pod installFrom this point, always open MyApp.xcworkspace, not MyApp.xcodeproj. Opening the project file ignores the Pods and you will see 'Flutter/Flutter.h' file not found.
Step 3: Run the engine and present a view
Flutter code runs inside a FlutterEngine. A FlutterViewController shows what the engine draws. Create the engine once, early, and reuse it. The following example keeps the engine in a small dependency object owned by the app delegate:
import UIKit
import Flutter
import FlutterPluginRegistrant
final class FlutterDependencies {
let engine = FlutterEngine(name: "main_engine")
init() {
engine.run()
GeneratedPluginRegistrant.register(with: engine)
}
}
@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let flutterDependencies = FlutterDependencies()
}
final class HomeViewController: UIViewController {
@objc func showFlutter() {
guard let app = UIApplication.shared.delegate as? AppDelegate else { return }
let flutterVC = FlutterViewController(
engine: app.flutterDependencies.engine,
nibName: nil,
bundle: nil
)
flutterVC.modalPresentationStyle = .fullScreen
present(flutterVC, animated: true)
}
}Three details matter here:
engine.run()starts the default Dart entrypoint, which ismain()in the module'slib/main.dart.GeneratedPluginRegistrant.register(with:)connects the plugins in your module'spubspec.yamlto this engine. If you skip it, plugin calls fail withMissingPluginException.- If you create
FlutterViewController()with no engine, Flutter makes a new one lazily. That works, but the first frame is slower and each screen gets its own engine. The caching chapter covers the trade-offs in detail.
SwiftUI hosts
SwiftUI has no direct view-controller presentation, so you wrap the controller. Keep the engine in an ObservableObject and share it through the environment:
import SwiftUI
import Flutter
import FlutterPluginRegistrant
final class FlutterDependencies: ObservableObject {
let engine = FlutterEngine(name: "main_engine")
init() {
engine.run()
GeneratedPluginRegistrant.register(with: engine)
}
}
struct FlutterScreen: UIViewControllerRepresentable {
@EnvironmentObject var dependencies: FlutterDependencies
func makeUIViewController(context: Context) -> FlutterViewController {
FlutterViewController(engine: dependencies.engine, nibName: nil, bundle: nil)
}
func updateUIViewController(_ controller: FlutterViewController, context: Context) {}
}
@main
struct MyApp: App {
@StateObject private var dependencies = FlutterDependencies()
@State private var showFlutter = false
var body: some Scene {
WindowGroup {
Button("Open Flutter") { showFlutter = true }
.fullScreenCover(isPresented: $showFlutter) {
FlutterScreen().ignoresSafeArea()
}
.environmentObject(dependencies)
}
}
}The .environmentObject modifier sits on the Button, which is the content that owns the presentation. The cover content inherits it from there.
App lifecycle events
Some plugins need to know about app lifecycle events such as push notification tokens, URL opens, or background fetch. Flutter's FlutterAppDelegate forwards those events to plugins. If your host's app delegate does not subclass it, you have two choices:
- Make your
AppDelegateinherit fromFlutterAppDelegate. This is the simplest approach when you own the delegate. - Keep your own base class and conform to
FlutterAppLifeCycleProvider. Then forward each delegate callback to aFlutterPluginAppLifeCycleDelegateinstance.
Plugins that rely on these events (push messaging is the common one) fail silently without forwarding. No error appears.
Run and test
Build and run the host from Xcode. The first build is slow, because the pod compiles the Dart code and the plugins. Later builds are incremental.
A few facts about debug builds surprise people:
- A debug build of a Flutter app on a physical device running iOS 14 or later can only be launched from Xcode or
fluttertooling. Tapping its icon on the home screen fails. Use a profile or release build to test standalone launch. - The simulator and device slices are both inside
Flutter.xcframework, so Apple Silicon simulators work. If a pod reports a missing arm64 simulator slice, check thatflutter_post_installis called. - Hot reload works only when the debug tooling is attached. The debugging chapter covers
flutter attach.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `pod install` says `podhelper.rb` not found | `.ios` folder was never generated, or the path is wrong | Run `flutter pub get` in the module and check `flutter_application_path` |
| `'Flutter/Flutter.h' file not found` | You opened the `.xcodeproj` | Open the `.xcworkspace` |
| Screen is black or white forever | Engine never ran, or the view controller was created before `run()` finished its setup | Call `run()` once and create the view controller from the same engine |
| `MissingPluginException` | Plugins were not registered on this engine | Call `GeneratedPluginRegistrant.register(with:)` after `run()` |
| Old Dart code shows after edits | Pods are stale | Run `flutter pub get`, then `pod install`, then a clean build |
| Build fails after adding a plugin to the module | Host pods were not refreshed | Run `flutter pub get` in the module, then `pod install` in the host |
| Custom build configuration names fail | The helper expects Debug, Profile, and Release names | Name host configurations to match, or follow the helper's naming rules for derived configurations |
Dismissing the Flutter screen
A FlutterViewController presented modally has no built-in way for Dart to close it. Pressing back in Dart only pops Dart routes. When the stack is empty, nothing happens. Use a platform channel so Dart can ask the host to dismiss:
- In Dart, call
MethodChannel('com.example.host/nav').invokeMethod('close'). - In Swift, register a handler on
engine.binaryMessengerfor the same channel name. Calldismiss(animated: true)whenclosearrives.
The channel API itself is covered in the platform channels chapter. The key point here is that navigation across the native/Flutter boundary is something you design, not something Flutter does for you.
Exercise
You run pod install successfully, open MyApp.xcworkspace, and build. The app launches, and tapping the button presents a blank Flutter screen. Your code is FlutterViewController(engine: engine, nibName: nil, bundle: nil), but engine.run() is never called. Plugin calls from Dart also throw MissingPluginException. What two lines are missing, and in which order should they run?
Show answer
engine.run() must be called to start the Dart entrypoint, and then GeneratedPluginRegistrant.register(with: engine) must be called to attach the module's plugins to that engine. Both belong in the code that creates the engine, before the view controller is presented.
Exercise
A teammate opens MyApp.xcodeproj and gets 'Flutter/Flutter.h' file not found, even though pod install succeeded for you. What is the cause and the fix?
Show answer
CocoaPods integrates pods through a workspace. The .xcodeproj file does not include the Pods project. Open MyApp.xcworkspace instead.