Sub topic 2
Integrating the module into an iOS app
This chapter assumes you know Swift, Xcode, and view controllers. You should already have a Flutter module, created as described in the earlier chapter, and CocoaPods installed.
Adding the module to your Xcode project
A Flutter module is a Flutter project that a native app embeds. You connect it through CocoaPods. In your app's Podfile, point to the module folder, load the module's podhelper.rb file, and call install_all_flutter_pods. Then run pod install and open the .xcworkspace file, not the .xcodeproj file.
Pre-warming and caching the Flutter engine
A FlutterEngine is the runtime that executes Dart code. Starting an engine takes time, so the first Flutter screen can appear slowly. You can start the engine early and keep one copy for reuse. The class below runs the engine once and stores it in a shared property.
import Flutter
import FlutterPluginRegistrant
final class FlutterHost {
static let shared = FlutterHost()
let engine = FlutterEngine(name: "main_engine")
private init() {
engine.run()
GeneratedPluginRegistrant.register(with: engine)
}
}Call FlutterHost.shared in application(_:didFinishLaunchingWithOptions:) so the engine starts at launch. Each FlutterViewController you create with engine: then reuses that engine.
> The engine runs in memory, so keep only one or two alive. Each one uses a noticeable amount of memory.
Talking to native code with platform channels
A platform channel is a named message path between native code and Dart. The host registers a handler under a name, and Dart calls that name with invokeMethod. The name must match exactly on both sides.
let channel = FlutterMethodChannel(
name: "com.example.host/session",
binaryMessenger: FlutterHost.shared.engine.binaryMessenger
)
channel.setMethodCallHandler { call, result in
switch call.method {
case "getUserName":
result("Ada")
default:
result(FlutterMethodNotImplemented)
}
}Register this handler before the Flutter screen calls the method. Dart calls invokeMethod<String>('getUserName') on a MethodChannel with the same name.
Exercise
Why must the Dart channel name and the Swift channel name match exactly?
Show answer
A MethodChannel routes calls by name. If the names differ, the message has no handler, and Dart receives a missing plugin or not-implemented error.