Flutter & Dart FFI: Calling Native Code from Dart
Flutter is a powerful UI toolkit, but sometimes you need to reach outside the Dart VM — into a C library, a system API, or a highly optimised native function. Platform channels are the traditional answer, but they carry boilerplate overhead and an asynchronous boundary that isn't always welcome. Dart FFI (Foreign Function Interface) gives you a lower-level, synchronous alternative: call a C function directly from Dart code, no Java or Kotlin or Swift glue required.
This article covers the fundamentals: loading a native library, binding to its functions, marshalling data, and avoiding the pitfalls that catch most people on their first FFI integration.
What is Dart FFI?
FFI is a mechanism that lets a high-level language call functions written in another language — typically C. Dart's FFI implementation, stabilised in Dart 2.12, lets you load a shared library (.so, .dylib, or .dll) at runtime, look up a symbol by name, and call it as if it were a regular Dart function. The Dart VM handles the calling convention and stack layout; you handle the type mapping.
The key package is dart:ffi, which ships with the Dart SDK. For Flutter projects targeting Android, iOS, macOS, Windows, or Linux, it's available without any additional dependency.
Project setup
Start with a Flutter app and a C source file. For this guide the C file is a simple math library — nothing exotic, so the focus stays on the FFI mechanics.
Create native/math_lib.c:
#include <stdint.h>
int32_t add(int32_t a, int32_t b) {
return a + b;
}
double multiply(double a, double b) {
return a * b;
}
You'll need a build system to compile this into a shared library per platform. CMake is the standard choice for Flutter plugins. Add a CMakeLists.txt alongside the C file:
cmake_minimum_required(VERSION 3.10)
project(math_lib)
add_library(math_lib SHARED math_lib.c)
set_target_properties(math_lib PROPERTIES
PUBLIC_HEADER math_lib.h
OUTPUT_NAME "math_lib"
)
For an actual Flutter plugin you'd integrate this into the plugin's build system so Gradle (Android) and Xcode (iOS/macOS) invoke CMake automatically. For desktop targets, the flutter_build system picks up a CMakeLists.txt in the platform folder directly.
Loading the library
In Dart, open the library with DynamicLibrary:
import 'dart:ffi';
import 'dart:io';
final DynamicLibrary _lib = () {
if (Platform.isAndroid) {
return DynamicLibrary.open('libmath_lib.so');
}
if (Platform.isIOS || Platform.isMacOS) {
// On Apple platforms, the library is statically linked into the binary.
return DynamicLibrary.process();
}
if (Platform.isWindows) {
return DynamicLibrary.open('math_lib.dll');
}
// Linux
return DynamicLibrary.open('libmath_lib.so');
}();
The platform branching is unavoidable — each OS has its own naming convention and linkage model. iOS requires static linking because App Store policy forbids loading unsigned dynamic libraries at runtime.
Binding to functions
With the library loaded, look up the add symbol and give it a Dart type:
// Define the C function signature as a Dart typedef
typedef AddC = Int32 Function(Int32 a, Int32 b);
// Define the Dart-callable equivalent
typedef AddDart = int Function(int a, int b);
final AddDart add = _lib
.lookup<NativeFunction<AddC>>('add')
.asFunction<AddDart>();
Two typedefs are always needed: one using FFI's NativeType annotations (Int32, Double, Pointer, etc.) that describes the C ABI, and one using plain Dart types that Dart code actually calls. asFunction() performs the conversion at lookup time — not at call time — so the overhead is paid once.
The multiply binding follows the same pattern:
typedef MultiplyC = Double Function(Double a, Double b);
typedef MultiplyDart = double Function(double a, double b);
final MultiplyDart multiply = _lib
.lookup<NativeFunction<MultiplyC>>('multiply')
.asFunction<MultiplyDart>();
Calling native functions
Once bound, the functions are called like any Dart function:
void main() {
print(add(3, 4)); // 7
print(multiply(2.5, 4)); // 10.0
}
The call is synchronous and happens on the calling thread. If the native function is fast (microseconds), this is fine. If it can block for milliseconds — network I/O, heavy computation — call it from an Isolate to avoid jank.
Working with pointers and structs
Primitive types are straightforward. Pointers and structs require more attention.
Suppose the C library exposes a struct:
typedef struct {
float x;
float y;
} Point;
void translate(Point* p, float dx, float dy) {
p->x += dx;
p->y += dy;
}
On the Dart side, declare the struct by extending Struct:
import 'dart:ffi';
final class Point extends Struct {
@Float()
external double x;
@Float()
external double y;
}
Allocate an instance using calloc from package:ffi:
import 'package:ffi/ffi.dart';
final ptr = calloc<Point>();
ptr.ref.x = 1.0;
ptr.ref.y = 2.0;
translate(ptr, 0.5, -1.0);
print('${ptr.ref.x}, ${ptr.ref.y}'); // 1.5, 1.0
calloc.free(ptr); // Always free manually — no GC here
Memory allocated through calloc lives outside the Dart heap. The GC does not track it. Forgetting to call calloc.free() is a memory leak — exactly the kind you'd get in C.
Strings
C strings (char*) need special handling. Use toNativeUtf8() and toDartString() from package:ffi:
import 'package:ffi/ffi.dart';
// Dart → C
final Pointer<Utf8> nativeStr = 'Hello, native!'.toNativeUtf8();
someNativeFunction(nativeStr);
calloc.free(nativeStr);
// C → Dart (when C allocates the string)
final Pointer<Utf8> result = getGreeting();
final String dartStr = result.toDartString();
// Don't free result if C owns the memory
Ownership matters more with strings than with any other type. Know whether Dart or C is responsible for freeing each allocation, and document it clearly.
Isolates and blocking calls
Long-running native functions block the calling thread. On Flutter's UI isolate, any blocking call over ~16 ms causes frame drops. The solution is to run blocking FFI calls in a background isolate:
import 'dart:isolate';
Future<int> heavyComputation(int input) async {
return Isolate.run(() => nativeHeavyFn(input));
}
Isolate.run(), available since Dart 2.19, spins up an isolate, runs the closure, and returns the result. The native function executes entirely off the UI thread.
One caveat: Pointer values cannot be sent across isolate boundaries directly. If the heavy function needs to work on a Dart-allocated native buffer, allocate it with calloc (which gives you an address that's valid across isolates) and pass the integer address, reconstructing the pointer on the other side with Pointer.fromAddress().
Annotations and ABI alignment
FFI annotations (@Int32(), @Float(), @Double()) tell the VM how to lay out struct fields in memory. They must match the C compiler's layout exactly. For standard types this is straightforward; for packed structs, bit fields, or platform-specific sizes (long is 32-bit on Windows, 64-bit on Linux) you need to be precise.
Use sizeOf<YourStruct>() at runtime and compare it against the C-side sizeof to catch mismatches early. A mismatch produces undefined behaviour that's indistinguishable from correct execution until it isn't.
When to use FFI vs platform channels
- Use FFI when you're calling a C library, a system API with a C interface, or compute-intensive code where the async overhead of platform channels adds up.
- Use platform channels when you need to call platform-specific high-level APIs (UIKit, SwiftUI, Jetpack Compose) or when the API doesn't have a C interface.
- Use plugins when the library already has a pub.dev wrapper. Don't write FFI bindings for something that already exists.
FFI is lower-level. You're responsible for memory management, type alignment, thread safety, and the possibility of crashing the Dart VM with a bad pointer. Treat it like C code — because it is.
Wrapping up
Dart FFI closes the gap between Flutter's high-level widget layer and the native world below it. Once you get past the typedef ceremony and the memory ownership rules, calling C from Dart is no more complicated than calling it from Python or Go. The main discipline it demands is the same one C always demands: know who owns every allocation, and free it exactly once.
For production use, look at the ffigen tool (package:ffigen), which generates Dart bindings automatically from C header files. It handles the typedef boilerplate and reduces the risk of type mismatches. Hand-written bindings are fine for learning and for small surfaces; ffigen is the right tool for a real C library with dozens of functions and structs.