← Back to posts Cover image for Mastering Flutter Native Interop: A Guide to FFI, JNI, and Pigeon for Plugin Development

Mastering Flutter Native Interop: A Guide to FFI, JNI, and Pigeon for Plugin Development

· 4 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

Flutter’s ability to bridge to native code is one of its superpowers, but for years, writing and maintaining those bridges has been complex. With recent stabilization of key tools, plugin development is becoming more reliable and efficient. If you’re a plugin maintainer or developer looking to integrate native libraries, understanding the new landscape is crucial. Let’s break down the three main tools you’ll use: FFIgen, JNIgen, and Pigeon.

The Core Tools: FFIgen & JNIgen

These are your foundation for directly calling native code.

FFIgen generates Dart bindings from C and Objective-C header files. This is a huge step forward for iOS/macOS interop. Previously, you’d manually write complex ffi bindings; now, you can generate them from your existing headers.

Imagine you have a simple C library for audio processing:

// audio_processor.h
#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
  float volume;
  float pitch;
} AudioSettings;

int process_audio_buffer(float* buffer, int length, AudioSettings settings);

#ifdef __cplusplus
}
#endif

With FFIgen, you can generate a type-safe Dart API automatically. You’d typically set this up in your pubspec.yaml under a ffigen config, run dart run ffigen, and get a Dart file you can use directly:

import 'generated_bindings.dart';

final dylib = DynamicLibrary.open('libaudio_processor.so');
final audioLib = AudioProcessor(dylib);

void process() {
  var settings = AudioSettings(volume: 0.8, pitch: 1.0);
  List<float> buffer = [0.1, 0.2, 0.3];
  final result = audioLib.process_audio_buffer(buffer.asPointer(), buffer.length, settings);
  print('Processed $result samples');
}

JNIgen performs a similar role for Android, generating Dart bindings from Java/Kotlin classes. This is perfect for calling Android system APIs or third-party AARs/JARs directly, bypassing the more cumbersome traditional MethodChannel boilerplate.

The Orchestrator: Pigeon

While FFIgen and JNIgen create the raw bindings, Pigeon is the higher-level tool that orchestrates the communication. It generates type-safe messaging code for both Dart and native platforms (Kotlin/Java, Swift/Obj-C) from a single interface definition. It’s the successor to manually writing and parsing MethodChannel messages.

Here’s the key: Pigeon can now use the stable FFIgen/JNIgen bindings under the hood (this is the “native interop” mode), making it more robust and performant than its older channel-based backend.

You define your API in a .dart file:

// messages.dart
import 'package:pigeon/pigeon.dart';

@HostApi()
abstract class DeviceInfoApi {
  @async
  BatteryInfo getBatteryInfo();
}

class BatteryInfo {
  int level;
  bool isCharging;
}

Run flutter pub run pigeon --input messages.dart with the appropriate config, and Pigeon generates the Dart interface and the native boilerplate. Your Dart code becomes clean and type-safe:

// In your Flutter app
final api = DeviceInfoApi();
final info = await api.getBatteryInfo();
print('Battery at ${info.level}%');

The generated native code uses the JNIgen (Android) and FFIgen (iOS) bindings for the actual communication, offering a significant upgrade in reliability and performance over the older channel system.

When to Use What? A Practical Guide

Choosing the right tool depends on your goal.

  1. Use FFIgen or JNIgen directly when you need maximum performance and control, or are integrating a specific native library (like a C audio codec or a system Android SDK). You’re working close to the metal.

  2. Use Pigeon with native interop for the vast majority of plugin development. It provides the best of both worlds: type-safe, high-level APIs for developers with the robustness and speed of the new stable backends. This is the recommended path for new plugins and for migrating existing ones.

  3. The older Pigeon (Channel-based) or direct MethodChannel are still functional but are now considered legacy for most interop scenarios. They lack the static type safety and performance benefits of the new system.

Common Mistakes & Migration Tips

  • Don’t Mix Generated Code Manually: Never edit the files generated by FFIgen, JNIgen, or Pigeon. Your changes will be overwritten. Treat them as build artifacts.
  • Handle Memory Carefully: When using FFI directly, you are responsible for memory allocation and lifetime, especially for strings and structs. Use allocator from package:ffi and consider using arena for short-lived allocations.
  • Start Small with Migration: If you have an existing plugin using MethodChannels, don’t rewrite everything at once. Pick a single, simple API endpoint and migrate it to Pigeon with native interop. The learning curve from the generated code will guide the rest.
  • Mind the Threads: Native code can block. For potentially long-running operations, always offload the work to a background isolate in Dart or use native background threads, and use the async patterns Pigeon provides.

The stabilization of FFIgen, JNIgen, and Pigeon’s native backend marks a turning point. It means plugin authors can spend less time debugging fragile channel communication and more time building powerful features. Start experimenting with these tools today—your future self, maintaining that plugin, will thank you.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.