Tutorial · 40 min · advanced
Build a plugin
Build the real, open-source share plugin and learn the whole anatomy of a dartnative plugin: Dart API, FFI bindings, the Swift and Kotlin bridges, and a hot-restart-safe async callback.
Finished code in our GitHub repository: tutorials/build_a_plugin
Every dartnative plugin is the same small machine: a Dart API your users call, a set of C-callable functions on the native side, and FFI wiring between them. No method channels, no codecs, no platform-channel threading rules: a Dart call is a native call.
This tutorial builds that machine end to end, twice over:
- You already maintain a Flutter plugin? Follow the porting thread. The
plugin we build,
dartnative_share, is itself a port ofshare_plus: the SDK-interaction code survives almost untouched, and everything we do is “replace the method channel with the pattern below”. Your accumulated SDK edge cases are the valuable part; carry them over. - Starting from scratch? Follow the steps. Each layer is a page of code, and by the end you’ll have the complete mental model.
And it’s real: dartnative_share is an official plugin, and its full
source is open: every snippet here is shipping code you can open,
diff, and copy from
(plugins/dartnative_share
in the public repo).
What you need
- The
dnCLI (get it on dartpub.dev; building and testing is free) - An iPhone or Android phone (share sheets are dull on simulators)
- Comfort reading a little Swift and Kotlin: you’ll write ~100 lines of each
- For the demo app on Android:
minSdk = 26inandroid/app/build.gradle.kts(dartnative_compressor’s floor; new projects default lower and the manifest merge fails)
How a plugin talks: thirty seconds of architecture
Dart API Share.share('hi')
│
FFI bindings lookupFunction('DNShareText') → direct C call
│
iOS @_cdecl("DNShareText") func … (Swift, in your pod)
Android DNShareText() → JNI → Kotlin (.so, in your AAR)
Two directions matter:
- Dart → native (this page, Part 1): synchronous C calls. Easy, safe, and 90% of every plugin.
- Native → Dart (Part 2): native calls you back later: a completion, an event. This is the one genuinely sharp corner of plugin authoring, and we’ll do it with the pattern that makes it crash-proof.
Part 1: the share plugin
Step 1: the package
A plugin is an ordinary Dart package with two extra blocks in pubspec.yaml.
The plugin.platforms block tells the toolchain how to link the native code;
the registrant block lets apps load your plugin with zero per-plugin setup:
name: dartnative_share
version: 0.1.0
dependencies:
dartnative: ^1.0.0
ffi: ^2.1.0
dartnative:
plugin:
platforms:
ios:
ffiPlugin: true # iOS: statically linked pod
android:
package: com.dartnative.share # Android: ALWAYS pluginClass,
pluginClass: DartNativeSharePlugin # never ffiPlugin (see below)
registrant:
imports:
- package:dartnative_share/dartnative_share.dart
calls:
- ShareFFIBindings.loadSymbols();
That registrant block is the whole app-integration story: when an app adds
your plugin and runs dn pub get, the generated
dartnative_plugin_registrant.dart picks up your loadSymbols() call
automatically. App developers add one dependency and touch nothing else.
Why
pluginClassand neverffiPlugin: trueon Android:ffiPluginonly bundles your.so: nothing ever callsSystem.loadLibrary, soJNI_OnLoadnever fires and the first callback crashes in_JavaVM::GetEnv. The ~20-linepluginClassfile in Step 5 exists to make that one call.
Step 2: the Dart API
Design the API you want users to have, as if the native side already existed. For sharing, that’s three static methods:
class Share {
Share._();
/// Present the system share sheet for [text].
static void share(String text) => ShareFFIBindings.shareText(text);
/// Share one file, with an optional MIME hint and caption.
static void shareFile(String path, {String? mimeType, String? text}) =>
ShareFFIBindings.shareFiles(
[path],
mimeTypes: mimeType == null ? null : [mimeType],
text: text,
);
/// Share several files at once.
static void shareFiles(List<String> paths,
{List<String>? mimeTypes, String? text}) =>
ShareFFIBindings.shareFiles(paths, mimeTypes: mimeTypes, text: text);
}
Porting note: this is share_plus’s surface, minus the parts a fresh start
doesn’t need. Keep your plugin’s public API shape: your users already know
it.
Step 3: the FFI bindings
The bindings class does three jobs: describe each C function’s signature,
resolve the symbols once at startup, and marshal Dart values into C memory
(and free it: every toNativeUtf8 is a malloc you own).
typedef _DNShareTextC = Void Function(Pointer<Utf8>);
typedef _DNShareTextDart = void Function(Pointer<Utf8>);
class ShareFFIBindings {
static late final _DNShareTextDart _shareText;
static bool _loaded = false;
static void loadSymbols() {
if (_loaded) return;
if (!Platform.isIOS && !Platform.isAndroid) return; // ALWAYS guard
final lib = Platform.isAndroid
? DynamicLibrary.open('libdartnative_share.so') // your .so
: DynamicLibrary.process(); // app binary
_shareText = lib.lookupFunction<_DNShareTextC, _DNShareTextDart>(
'DNShareText',
);
_loaded = true;
}
static void shareText(String text) {
final ptr = text.toNativeUtf8();
try {
_shareText(ptr); // native copies during the call…
} finally {
calloc.free(ptr); // …so we free immediately after
}
}
}
Three rules that hold for every plugin:
- Guard the platform.
registerAll()runs unconditionally on every platform; without the guard your plugin crashes symbol lookup on the platforms it doesn’t support. - iOS resolves from the process, Android from your
.so. iOS pods are statically linked into the app binary; Android ships a separate library. - You own what you allocate. Native copies strings synchronously
during the call, so
freein afinallyright after. (Arrays of strings, seeshareFilesin the real source, are the same rule applied in a loop.)
Step 4 (iOS): one Swift file
The entire iOS side is @_cdecl functions in your pod. @_cdecl gives a
Swift function a C name and ABI. That’s what lookupFunction finds:
// ios/Classes/DNShareBridge.swift
import UIKit
@_cdecl("DNShareText")
public func DNShareText(_ textPtr: UnsafePointer<CChar>?) {
guard let textPtr = textPtr else { return }
let text = String(cString: textPtr) // copy NOW — Dart frees after we return
guard !text.isEmpty else { return }
DispatchQueue.main.async { // UIKit work → main thread
presentShareSheet(items: [text])
}
}
private func presentShareSheet(items: [Any]) {
guard let vc = topViewController() else { return }
let activity = UIActivityViewController(
activityItems: items, applicationActivities: nil)
// iPad: anchor the popover or UIKit asserts.
if let popover = activity.popoverPresentationController {
popover.sourceView = vc.view
popover.sourceRect = CGRect(x: vc.view.bounds.width / 2, y: 0,
width: 1, height: 1)
}
vc.present(activity, animated: true)
}
Porting note: presentShareSheet and the top-view-controller walk are the
kind of code you lift from your Flutter plugin verbatim: only the entry
point changed, from a method-channel handler to @_cdecl.
Step 5 (Android): Kotlin + a thin JNI layer
Android has three small pieces. First, the pluginClass from Step 1. Its
only job is loading your library at engine attach:
class DartNativeSharePlugin : FlutterPlugin {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
System.loadLibrary("dartnative_share") // fires JNI_OnLoad below
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {}
}
Second, the C++ bridge. JNI_OnLoad caches the JVM and your Kotlin method
IDs once; each FFI entry converts C strings to Java and forwards:
extern "C" __attribute__((visibility("default")))
void DNShareText(const char* text) {
JNIEnv* env = getEnv();
if (!env || !g_bridgeClass || !g_shareText) return;
jstring jText = env->NewStringUTF(text ? text : "");
env->CallStaticVoidMethod(g_bridgeClass, g_shareText, jText);
env->DeleteLocalRef(jText);
if (env->ExceptionCheck()) env->ExceptionClear();
}
Third, the Kotlin that does the actual work, and here the porting story
shines: this is share_plus’s intent building, kept as-is (ACTION_SEND,
the FileProvider copy-and-vend dance, MIME reduction for multi-file
shares), with the method-channel dispatch deleted:
@Keep
fun shareText(text: String?) {
if (text.isNullOrEmpty()) return
Handler(Looper.getMainLooper()).post { // UI work → main thread
val intent = Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, text)
}
startChooser(Intent.createChooser(intent, null))
}
}
(The file-sharing path, the bundled FileProvider, and the manifest
<queries> block are in the open source. They merge into consuming apps
automatically, so app developers configure nothing.)
Step 6: run it
The finished demo app for this tutorial is
tutorials/build_a_plugin,
a byte-identical copy of the share plugin’s own example app: pick
photos or videos from the gallery (via dartnative_media_picker, with
video poster frames from dartnative_compressor), type a caption, and
share any of it:
cd tutorials/build_a_plugin
dn create . # generates the ios/ + android/ shells, then fetches deps
dn run
Tap Share text only: the real system sheet slides up. That’s the
whole Part 1 machine: one Dart call, straight through FFI, into UIKit or
an Android Intent. Share picked items exercises the same machine
through Share.shareFiles: one or many files with the caption along.
Part 2: the callback, shareWithResult
Here’s a question Part 1 can’t answer: did the user actually share?
Apps want this constantly: analytics (“shared via WhatsApp”), reward flows
(“share to unlock”), or just a honest “thanks!” toast. share_plus calls it
shareWithResult, and we’ll add it now:
final result = await Share.shareWithResult('Join me: https://…');
if (result.status == ShareResultStatus.success) {
analytics.log('shared_via', result.raw); // e.g. com.whatsapp/…
}
We saved it for last deliberately, because it’s more than a feature: it’s the chapter where your plugin crosses into the one part of plugin authoring that requires specific care: native code calling Dart back later.
Why “later” is dangerous
When Dart hands a callback to native code, native receives a plain C
function pointer the Dart VM generates. Now picture debugging your app:
the share sheet is open, and you press hot restart (capital R). Dart
throws the whole program away and runs main() again, in the same OS
process. Every function pointer from the old run is deleted. But the share
sheet is still on screen, and when the user taps a target, iOS fires the
completion handler… into a deleted pointer:
error: Callback invoked after it has been deleted. → SIGABRT
The app dies instantly. It’s debug-only (release apps never hot-restart), but it will kill every debugging session of every developer using your plugin. The framework can’t intercept the call (native invokes the pointer directly), so plugins must deliver callbacks with a pattern that is safe by construction. dartnative ships one: the dispatcher slot.
The dispatcher slot, in four steps
- Dart creates ONE callback pointer for the whole plugin and hands its
address to native. Every call carries a
tokenso one pointer serves many requests. - Native stores it in ONE variable (“the slot”) and registers that slot
with the framework (iOS:
DNRegisterAsyncDispatcherSlot; Android: capture the framework’s restart counterDN_IsolateGen()next to the pointer). - Before every call into Dart, native re-checks (slot still non-zero / counter unchanged) and always calls on the main thread.
- On hot restart the framework zeroes the slot and bumps the counter while the old pointer is still valid. So a fire before that hits a live pointer (harmless), and a fire after reads 0 and drops. There is no moment where a deleted pointer can be called, and when your plugin re-initialises in the new session, the slot refills automatically.
Dart: dispatcher, tokens, futures
// (token, status, raw) — status: 0 dismissed, 1 success, 2 unavailable.
typedef _ShareResultDispatchC = Void Function(Int64, Int32, Pointer<Utf8>);
void _dispatchShareResult(int token, int status, Pointer<Utf8> raw) {
ShareFFIBindings._completeResult(
token, status, raw == nullptr ? '' : raw.toDartString());
}
final _dispatchPtr =
Pointer.fromFunction<_ShareResultDispatchC>(_dispatchShareResult);
// In loadSymbols(): _setDispatcher(_dispatchPtr.address);
// Per request: park a Completer under a fresh token…
static Future<ShareResult> shareTextWithResult(String text) {
final token = _nextToken++;
_pending[token] = Completer<ShareResult>();
/* …call DNShareTextWithResult(token, text)… */
return _pending[token]!.future;
}
A result for a token from before a hot restart finds no completer and is simply ignored. Everything self-heals.
iOS: the slot + the completion handler
private let _dispatcherSlot: UnsafeMutablePointer<Int64> = {
let p = UnsafeMutablePointer<Int64>.allocate(capacity: 1)
p.pointee = 0
return p
}()
@_cdecl("DNShareSetDispatcher")
public func DNShareSetDispatcher(_ callbackPtr: Int64) {
_dispatcherSlot.pointee = callbackPtr
// Register once: the framework zeroes this slot BEFORE the old
// isolate dies on hot restart.
if let sym = dlsym(UnsafeMutableRawPointer(bitPattern: -2),
"DNRegisterAsyncDispatcherSlot") { /* …register… */ }
}
/// EVERY delivery goes through here — main thread, fresh slot read.
private func fireShareResult(token: Int64, status: Int32, raw: String) {
DispatchQueue.main.async {
let addr = _dispatcherSlot.pointee // read FRESH — never cache
guard addr != 0 else { return } // hot restart happened → drop
raw.withCString {
unsafeBitCast(addr, to: ShareResultDispatch.self)(token, status, $0)
}
}
}
The share sheet already has the hook we need.
completionWithItemsHandler tells us exactly what happened:
activity.completionWithItemsHandler = { activityType, completed, _, _ in
fireShareResult(token: token,
status: completed ? 1 : 0,
raw: activityType?.rawValue ?? "")
}
Three rules keep the guarantee (break any one and the crash returns): never copy the raw address into a closure or field; register the slot once; re-check before every fire, on the main thread.
Android: the generation gate + the chooser receiver
Android’s invalidation signal is a restart counter instead of a slot. Capture it next to the pointer, compare before every delivery:
@Volatile private var dispatcherPtr: Long = 0L
@Volatile private var dispatcherGen: Long = 0L
fun setDispatcher(ptr: Long) {
dispatcherPtr = ptr
dispatcherGen = nativeIsolateGen() // capture WITH the pointer
}
internal fun deliverShareResult(token: Long, status: Int, raw: String) {
Handler(Looper.getMainLooper()).post {
if (dispatcherGen != nativeIsolateGen()) return@post // restarted → drop
val ptr = dispatcherPtr
if (ptr == 0L) return@post
nativeDeliverShareResult(ptr, token, status, raw)
}
}
The “which app did they pick” signal comes from the chooser itself: pass an
IntentSender to Intent.createChooser, and the system broadcasts the
chosen ComponentName to your receiver (mind FLAG_MUTABLE on Android
12+; the system must be able to fill the extra in):
class ShareResultReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val token = intent.getLongExtra(EXTRA_SHARE_TOKEN, -1L)
val component: ComponentName? = /* EXTRA_CHOSEN_COMPONENT */
deliverShareResult(token, 1, component?.flattenToString() ?: "")
}
}
One honest platform gap: Android’s chooser reports selections only.
Dismissing it fires nothing. The plugin detects dismissal Dart-side: the
chooser pauses your app, so when the app resumes with the request still
unanswered, a short grace window resolves it as dismissed. iOS needs none
of this: its completion handler reports both outcomes exactly.
Test the sharp corner
Run the demo, tap Share text with result, and while the sheet is open
press capital R in the terminal (lowercase r is hot reload and
doesn’t reproduce the hazard: the isolate must be torn down). Then pick a
target.
Nothing happens, and that’s the win. The selection lands in native code, reads a zeroed slot / stale generation, and drops. Without the pattern, that tap is a SIGABRT. Comment out the slot registration and try again if you want to see the crash you just designed away; then run the app fresh and watch the result label update on share and on dismiss.
Shipping it
- Structure:
lib/+ios/Classes/*.swift+ a podspec +android/(Kotlin, one.cpp,CMakeLists.txt). The open-source plugin is the canonical layout. - ViewType: this plugin has no view. If yours does, claim your index
with
ViewType.claim('com.you.plugin/view'). Never hardcode an integer. - The full authoring reference (provider templates for view plugins,
library-loading rules, string-lifetime rules, packaging):
docs/plugin_development.mdand its callback companiondocs/plugin_async_callbacks.mdin the public repo.
Why this is native
Share.share()is a direct C call intoUIActivityViewController/Intent.createChooser, the same code paths a hand-written native app uses, with no channel serialization between you and the OS. And the result callback rides the platform’s own completion signals, delivered back into Dart through a pointer the framework guarantees can never dangle.
The finished code
In the public repo at tutorials/build_a_plugin: dn create .,
dn run. The screen (lib/share_demo.dart) is a byte-identical copy of
the share plugin’s example app, so improvements to the example flow into
this tutorial by copying the file again. The plugin it exercises is fully
open at plugins/dartnative_share: ~400 lines across Dart, Swift,
Kotlin, and C++, the complete anatomy this article walked through, in
production form.