Flutter and Native Code: Platform Channels, C++, Rust, and FFI

Technical graphic comparing Rust and C
Externally sourced image from Databento. Attribution and reuse rights have not yet been verified. · View original image

“Write it into Rust” does not automatically convert a Flutter algorithm into a faster algorithm. The native code can help with a consolidated library, specific access to an SDK or a calculation burden that justifies the border. It also introduces new problems: buffer ownership, ABI types, architecture compilation, shortcuts on the right thread, native crash and a second string of tools.

The engineering decision isn’t Dart versus Rust. It’s how much responsibility each run holds and how much it costs to cross the border. That article uses Flutter 3.50 / Dart 3.14 and Rust 1.100 as a documentary baseline, without assuming that a project is already migrated to these versions. Flutter interop documentation’s documentation distinguishes direct links generated by ffigen / jnigen and multiplatform contracts generated by Pigeon. The examples are replaceable designs and fragments; there are no established benchmarks and no measured performance figures **.

Technical diagram accompanying Flutter and Native Code: Dart, Platform Channels, C++, Rust, and FFI
Original editorial chart. The native border requires monitoring serialization, concurrence and memory property.

The right problem for each tool

Let’s think about an app that processes images for an editor: The IU modifies parameters, a filter transforms million bytes and a platform API keeps the final file. There are at least three different operations:

  1. Interface status and product rules. They fall into Dart and Flutter’s state architecture and require no native bridge.
  2. CPU-bound Transformation. Can be put into Dart at an isolate, C / C++ or Rust.
  3. Access to a system service. Can require Android / iOS and a platform plugin; doesn’t mean that that SDK has to be rewritten at Rust.

Before inserting native code, I would consider Uint8List, ByteData, apis SIMD or existing libraries and an isolate to avoid blocking the main isolate. If the Dart algorithm meets latency, memory and maintenance, introduce FFI is complexity without a proven justification.

Original conceptual illustration accompanying Flutter and Native Code: Platform Channels, C++, Rust, and FFI; not a screenshot.
Original conceptual illustration of this article's topic; not a screenshot or measured result.

Four families of interop that aren’t equivalent

ApproachWhat’s his report?better tuningMain cost
Pure dartFunction / class and message between isolatesMultiplatform logic and sufficient algorithms at DartCPU, GC, copies between isolates by data and API
Platform ChannelsDart messages ↔ host implementationExisting platform API, Grain events and operationsSerialization and contract of messages, threatening / platform
PigeonSection 3Multiplatform API Plugins that seek to avoid ad hoc stressesGeneration, contract version and error management
dart:ffi / FIGENABI / bindings C symbolsLibraries C, C++ with backer C, Rust with interface CCouples, memory, lifecycle, build and ABI
jnigenJava / Kotlin classes exposed by JNIAndroid libraries that demand direct Java bindingsJNI, threats, permissions, lifecycle Android

Flutter distingue Flow backtom-up from ffigen / jnigen - from leading or existing classes - from Flow top-down from Pigeon - first design a neutral contract. Pigeon uses Platform Channels as his documented stable modality while his direct native interp modality appears explicitly as preview. A “stable direct interop at Flutter 3.50” with an “currently stable Pigeon native interop” should not be confused. See Pigeon.

For C and ObjectiveC, the supported path is FFIgen and for Java / Kotlin and JNIgen. None by itself converts an API designed for UI yarn into a secure call function from a worker or automatically resolves how to release shared memory.

A Plugin architecture with observable boundaries

I propose to separate three levels into a processing library:

Flutter widgets / estado / gestos
    │
    ├─ API idiomática de Dart (validación, errores, cancelación)
    │     │
    │     ├─ algoritmo Dart puro o isolate
    │     ├─ plugin Platform Channel / Pigeon → API de sistema
    │     └─ binding FFIgen → C ABI → biblioteca Rust/C++
    │
    └─ presentación del resultado + medición de frame timings

The domain cape should receive and return concrete types and manage faults without knowing details of Pointer, JNIEnv or other buffers. The native plugin should declare architecture / OS supported, ABI version, loading mechanisms and cancellation contract. A uniform interface allows to compare implementations without simultaneously changing the IU.

From Flutter 3.38, guía oficial de FFI recommends package_ffi with built hooks and native assets for new integrations. It does not mean that all historic plugins require immediate migration: there are existing plugins with Gradle, Cocoa-Pods, CMake or precompiled binaries and specific requirements.

Minimum example: A C ABI limit shared by C++ and Rust

Suppose a function that adds a byte buffer and returns a uint64_t. This example serves to explain ownership, but not to gain a sign: the kernel is too simple to justify a native library in a real application.

/* include/checksum.h: firma pública estable para código nativo. */
#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/* data debe apuntar a len bytes válidos durante la llamada.
   len == 0 devuelve 0 sin leer el puntero. */
uint64_t checksum_bytes(const uint8_t *data, size_t len);

#ifdef __cplusplus
}
#endif

A C++ implementation can preserve internal class, temperates and optimization but should display a extern "C" function: ffigen does not directly interpret a C++ class ABI and does not guarantee its layout or name maneling.

#include "checksum.h"

extern "C" uint64_t checksum_bytes(const uint8_t* data, size_t len) {
  if (len == 0) return 0;
  if (data == nullptr) return 0;  // Error debe tratarse en el contrato real.
  uint64_t sum = 0;
  for (size_t i = 0; i < len; ++i) sum += data[i];
  return sum;
}

For Rust 2024, the equivalent requires an explicit unsafe border and a more production-rich error policy. It is assumed that with the exception of a zero length, the pointer meets the documented conditions:

use std::ffi::c_uchar;

/// # Safety
/// Si `len > 0`, `data` debe apuntar a `len` bytes válidos,
/// contiguos, inicializados y accesibles durante toda la llamada.
/// No debe existir una escritura concurrente incompatible.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn checksum_bytes(data: *const c_uchar, len: usize) -> u64 {
    if len == 0 || data.is_null() {
        return 0;
    }
    // SAFETY: lo garantiza el llamador mediante el contrato anterior.
    let bytes = unsafe { std::slice::from_raw_parts(data, len) };
    bytes.iter().map(|&byte| u64::from(byte)).sum()
}

It cannot be compiled both implementations with the same symbol within a single library and are alternatives to comparable built up. In production, the API should distinguish invalid NULL from a legitimate result 0, define length limits and manage errors without throwing C++ exceptions or make pics that cross ABI without control. Rust reduces some memory faults within his secure code, doesn’t come back secure an arbitrary FFI border. The Rustonomicon explain ABI, pointer and unwind requirements.

What about the Dart side?

The binding should preserve ABI (size_t) and check that the buffer remains alive while calling. Generate binding with ffigen from the header prevents some manual translation but does not check the temporary validity of a direction and the immutability of shared memory. A regular Uint8List should not be treated as a stable C pointer without an interop mechanism that will guarantee its conditions. We normally have to create or acquire native storage, transfer bytes and free it with its proper policy.

No Fictitious malloc / free “solution” is shown without specifying what run the buffer assigned: an essential FFI rule is that memory reserve defines how it’s released, with the exception of an explicit contract that indicates otherwise. The documentación de Dart FFI and NativeFinalizer have been established with the right lifetime. Fintiers are a last resort cleaning mechanism and do not replace a determinist dispose as required by the API.

Isolates, event loop and yarn affinity

To move the calculation to Rust doesn’t avoid Jank if Dart sincerely invokes it from the main isolate and takes tens of milliseconds. A synchronous FFI function consumes time in the thread that calls it. Also, “using Isolate.run” for any library is insufficient: they have to review their native apis thread interminance, resource initialization, ownership and how their results come back.

Flutter differentiates isolate principal, event loop y workers. On Android, many APIs demand the main thread of the host and iOS and UIKit parts as well. Pigeon defines contracts but does not nullify an SDK’s enforcement rules. If native callback arrives from an alien thread, NativeCallable’s OPIs have modalities and restrictions that have to be read before capturing Dart functions.

A right decision separates: threat that runs the kernel, * threat that manages the message **, * isolate that holds the status and * threat that allows the system API. That’s four different concepts but sometimes they match physically.

Where does flutter _ run _ bridge fit in?

flutter_rust_bridge provides production of binds and models suitable for Rust’s apis from Flutter. It reduces boiler plate but adds its own codegan, tooling, versions and support cycle. At the date of referral of the dossier, the observed release was v2.14.0-beta.2 and a beta should be increased to universal production recommendation without testing toolchain, platform and bug model.

It’s a reasonable choice when the computer wants to put forward more expressive Rust models and operations but does not replace the design of ownership, ABI validation, proper threat monitoring and platform packaging test. For a very small C API, ffigen + C ABI can be sufficient and for an existing Android SDK, jnigen or a plugin can best represent integration.

How to decide if native’s worth

Comparison should consider at least five dimensions:

DimensionMedicable question
CorrectionsDo the outputs match byte to byte with a reference implementation in inputs, boundaries and errors?
LatencyHow long does p50 / p95 / p99 of the kernel, of the dresper, of the so called FFI and of the complete IU flow?
ThroughHow many buffers do we process for a second with a defined concurrence, without memory breaking?
ReportHow much do you copy, book and retain at Dart and the native heap?
IntegrationHow many architecture and platforms compile, prove and maintain with the same semantics?

There’s no universal winner. An algorithm that passes 1,000 times through FFI with minuscule buffers can pay more in production and copies than the kernel that I wanted to accelerate. Another that processes a large buffer in a single operation can amortise that cost. A quick C++ with a CPU logo can continue to be worse if built or multiplatform support consumes more engineering time than saving.

Proposed benchmarking protocol: Dart, Rust and C++

Status: NOT EXECUTED. The goal would be to compare exactly a byte transformation with three equivalent kernel, without introducing different optimization during first measurement.

  1. Corpus synthetic with seed. Buffers with 1 KiB, 64 KiB, 1 MiB and 16 MiB, as well as non-aligned gaps and lengths and record an expected input and output hash.
  2. Correctness first. Golden tests and property tests: boundaries, endeniness, overflow, offsets, empty memory, invalid entry and call round-trip.
  3. versions and environment. Flutter / Dart, Rust / C++ compiler, optimization lights, AOT, NDK or Xcode, architecture, CPU, temperature, OS and physical device. Do not extrapolate a simulator to a phone.
  4. Layer measurement. T_total = T_prepare + T_boundary + T_kernel + T_return + T_dispose; compare native kernel separately from the Dart cost of packaging. The formula defines what to observe, does not assume that terms are always independently measurable.
  5. Warm-up and noise. Repetitions, cache policies, random order of variants, thermal throttling, CPU frequency and variability. Reporting distributions, not just an average.
  6. actual IU. Filling frame timings in model profile about appropriate device and how many frames lose budget and if an isolate releases the IU. Avoid using debug times as release results.
  7. Operating ergonomics. To register build faults, device size, CI complexity, number of platforms and code review load.

Flutter DevTools Performance allows you to study frames and timeline and does not automatically identify what part of an FFI call is slow. For native memory bugs, sanitizers and tools should be selected by platform. The documentación reciente de Android NDK recommends HWASan on compatible devices and should not promise that AddressSanitizer classic will be the supported option for any current Android.

Lifecycle and border failures

A native layer adds bug types that Dart cannot capture as regular exceptions. Invalid access can end the process. The cases that should get into CI include:

  • Nil and extreme length points rejected before to get into functions that await valid memory.
  • Callbacks that come from different threats and are delivered with the right mechanism; closure of the resort before / after the call.
  • Cancellation of long operations without memory while a worker keeps reading them.
  • Packaging and uploading of libraries at Android ARM64, iOS arm64 and other targets really supported without assuming that a local build equals everyone.
  • Panics, exceptions and native errors transformed to a stable result, never presenting the crash as a recoverable Dart exception.
  • Unicode and type / structure tests if the contract exposes more than just binary buffers.

The size of the bundle and the upgrade area count on the decision. A native dependence can be attached to an NDK, an SDK or an evolving ABI, and setting versions and testing the final device has a real cost.

Integration with the rest of the blog

The artículo sobre entornos reproducibles looks at what solve declared toolchains. To Flutter’s native concern this becomes concrete: an CI compilation requires knowing the Flutter’s SDK, Dart’s version, Rust / C++, the compiler and ABI of each target. Unversed variables make “in my machine compiles” a weak property.

And if the native component connects with hardware - for example, a point-of-sale printer - the border gets bigger: they no longer only matter CPU, memory or JNI but transport, firmware, page code, physical states and reattempts. That problem’s about ESC/POS: tickets térmicos fiables.

Conclusion

The well-designed native interoperability begins with a domain question and a verifiable contract, and with a preferred language. Dart remains a serious alternative for numerous kernel and an isolate can solve UI blockade without FFI. Pigeon and Platform Channels are suitable for host APIs and JNIGan and FFIGan come up with existing libraries with other guarantees and risks. Rust and C++ provide powerful tools if their integration costs are warranted.

Without equivalent proof of correctness, latency, memory and frames conduct, talking about “Rust 3 × faster” would be advertising, non-engineering.

Primary references