Answer
Overview
Dart FFI (Foreign Function Interface) allows Dart code to directly call functions written in C (or other languages compiled to native shared libraries). It bridges Dart and native code without a platform channel.
When to Use Dart FFI
| Use Case | Example |
|---|---|
| Performance-critical code | Image processing, encryption |
| Existing C/C++ libraries | OpenCV, SQLite, libssl |
| Platform APIs not in Flutter | Direct OS calls |
| No method channel overhead | Real-time audio, DSP |
Basic FFI Example
dart// lib/native_math.dart import 'dart:ffi'; import 'dart:io'; // Load the shared library final DynamicLibrary nativeLib = Platform.isAndroid ? DynamicLibrary.open('libnative.so') : DynamicLibrary.process(); // iOS links statically // C function signature: int add(int a, int b); typedef AddC = Int32 Function(Int32 a, Int32 b); typedef AddDart = int Function(int a, int b); // Look up the function final add = nativeLib.lookupFunction<AddC, AddDart>('add'); void main() { print(add(3, 4)); // Calls native C: 7 }
C Code Side (native_math.c)
c// native_math.c #include <stdint.h> int32_t add(int32_t a, int32_t b) { return a + b; } // More complex example double calculate_average(double* arr, int32_t length) { double sum = 0; for (int i = 0; i < length; i++) sum += arr[i]; return sum / length; }
FFI Types Mapping
| Dart FFI Type | C Type | Dart Type |
|---|---|---|
text | text | text |
text | text | text |
text | text | text |
text | text | text |
text | text | text |
text | text | text |
text | text | text |
text | text | text |
With Strings and Structs
dartimport 'dart:ffi'; import 'package:ffi/ffi.dart'; // For Utf8 support // Calling C function that takes/returns strings typedef GetMessageC = Pointer<Utf8> Function(); final getMessage = nativeLib .lookupFunction<GetMessageC, Pointer<Utf8> Function()>('get_message'); final messagePtr = getMessage(); print(messagePtr.toDartString()); // Convert C string to Dart String
FFI vs Platform Channels
| Feature | FFI | Platform Channels |
|---|---|---|
| Language | C/C++ | Native (Swift/Kotlin) |
| Overhead | ✅ Very low | ❌ Message passing |
| Complexity | High | Medium |
| Use case | Performance-critical math/crypto | Platform UI, sensors |
Note: FFI is powerful but complex. For most Flutter plugins, Method Channels are simpler. Use FFI when you need direct C library access with minimal overhead.