0Pricing
Flutter Mobile Development · Lesson

Background Isolates and Native Memory Management

Run FFI calls off the main isolate and manage native allocations to avoid leaks.

Why FFI Belongs Off the Main Isolate

Dart's FFI lets you call native C functions directly, but those calls run synchronously on whatever isolate invokes them. If a native function is slow (image decoding, crypto, parsing a large buffer), running it on the main isolate blocks the UI thread and drops frames.

  • The Flutter UI runs on the root (main) isolate; jank appears when it stalls more than ~16ms.
  • Native code has no awareness of Dart's event loop. A 200ms C call freezes the app.
  • The fix: run heavy FFI work on a background isolate so the main isolate stays free to paint.

This lesson covers spawning isolates, sharing native pointers safely, and freeing native memory without leaks.

Isolates vs Threads: The Memory Model

A Dart isolate is an independent worker with its own memory heap and event loop. Unlike OS threads, isolates do not share Dart objects — they communicate by passing messages over ports.

  • Each isolate has its own GC heap; you cannot pass a normal Dart object by reference between them.
  • But native memory is different: a Pointer<T> from dart:ffi is just an integer address into the process's shared native heap.
  • That address is valid in any isolate of the same process — so FFI pointers can be shared across isolates, unlike Dart objects.

This distinction is the key to coordinating FFI work between isolates: you pass the address, not the object.

All lessons in this course

  1. Calling C Libraries with dart:ffi
  2. Type-Safe Platform Channels with Pigeon
  3. Writing Custom Platform Plugins for iOS and Android
  4. Background Isolates and Native Memory Management
← Back to Flutter Mobile Development