Plugins and extensions

suggest change

Extensibility in the Dart ecosystem spans two key dimensions: language-level extensions (extension methods and extension types that augment APIs without inheritance) and package-level plugins (modular packages that bridge Dart code to native platform capabilities or native C/Rust libraries).


Language Extensions

Dart offers two powerful compile-time extension mechanisms: extension methods (introduced in Dart 2.7) and extension types (introduced in Dart 3.3).

Extension Methods

Extension methods allow you to add new functions, getters, setters, and operators to any existing type—including core types like String, List, or third-party classes—without subclassing or modifying the original source code.

// Define an extension on String
extension StringTransformations on String {
  // Method to capitalize the first letter
  String capitalize() {
    if (isEmpty) return this;
    return '${this[0].toUpperCase()}${substring(1)}';
  }

  // Getter for convenience
  bool get isEmail {
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    return emailRegex.hasMatch(this);
  }

  // Operator overload
  String operator *(int times) => List.filled(times, this).join();
}

void main() {
  final greeting = 'hello world';
  print(greeting.capitalize()); // "Hello world"
  print('test@example.com'.isEmail); // true
  print('dart' * 3); // "dartdartdart"
}

Generic Extensions

Extensions can be parameterized with generic type constraints:

extension ListMath<T extends num> on List<T> {
  num sum() => fold(0, (acc, item) => acc + item);

  double average() {
    if (isEmpty) return 0.0;
    return sum() / length;
  }
}

void main() {
  final numbers = [10, 20, 30, 40];
  print('Sum: ${numbers.sum()}'); // 100
  print('Average: ${numbers.average()}'); // 25.0
}

Resolving Extension Conflicts

When two imported libraries declare extensions with identical method names, you can explicitly wrap the object in the extension name to disambiguate:

// Explicit invocation
final formatted = StringTransformations(name).capitalize();

Extension Types (Dart 3.3+)

Extension types are zero-cost abstractions over an underlying representation type. At compile time, the compiler enforces the new type and prevents accidental mixing with other primitives, while at runtime, no wrapper object is allocated.

// Zero-cost compile-time wrapper around int
extension type const UserId(int id) {
  // Validate or enforce constraints
  bool get isSystemAdmin => id == 0;
  
  void printBadge() {
    print('User #$id');
  }
}

void main() {
  final UserId admin = UserId(0);
  final UserId user = UserId(1042);

  print(admin.isSystemAdmin); // true
  user.printBadge();           // "User #1042"
  
  // int cannot be passed where UserId is explicitly required
}

Package Plugins in Dart and Flutter

In Dart terminology:

Federated Plugin Architecture

Modern plugins follow the federated architecture, separating concerns into distinct packages:

  1. App-facing package (my_plugin): The user-facing API that client applications import and interact with.
  2. Platform interface package (my_plugin_platform_interface): Defines the abstract interface class (MyPluginPlatform) that platform implementations must conform to.
  3. Platform implementations (my_plugin_android, my_plugin_ios, my_plugin_web, etc.): Concrete implementations using platform channels, JNI, FFI, or JS interop.
my_plugin/
├── my_plugin/                    # App-facing package
├── my_plugin_platform_interface/ # Abstract interface & token registration
├── my_plugin_android/            # Android Kotlin/Java implementation
├── my_plugin_ios/                # iOS Swift/Obj-C implementation
└── my_plugin_web/                # Web JS interop implementation

Platform Interface Pattern

In my_plugin_platform_interface:

import 'package:plugin_platform_interface/plugin_platform_interface.dart';

abstract class DeviceBatteryPlatform extends PlatformInterface {
  DeviceBatteryPlatform() : super(token: _token);

  static final Object _token = Object();
  static DeviceBatteryPlatform _instance = MethodChannelDeviceBattery();

  static DeviceBatteryPlatform get instance => _instance;
  static set instance(DeviceBatteryPlatform instance) {
    PlatformInterface.verifyToken(instance, _token);
    _instance = instance;
  }

  Future<int> getBatteryLevel() {
    throw UnimplementedError('getBatteryLevel() has not been implemented.');
  }
}

Native FFI Plugins (dart:ffi)

For high-performance native integrations (such as SQLite, image processing, cryptography, or audio engines written in C, C++, or Rust), Dart supports FFI plugins without requiring platform channel serialization:

In pubspec.yaml:

name: native_crypto
description: High performance crypto bindings via Dart FFI
version: 1.0.0

flutter:
  plugin:
    platforms:
      android:
        ffiPlugin: true
      ios:
        ffiPlugin: true
      macos:
        ffiPlugin: true
      windows:
        ffiPlugin: true
      linux:
        ffiPlugin: true

Dart binding with dart:ffi:

import 'dart:ffi';
import 'dart:io';

typedef NativeHashFunc = Int32 Function(Pointer<Uint8>, Int32);
typedef DartHashFunc = int Function(Pointer<Uint8>, int);

class NativeCryptoEngine {
  late final DynamicLibrary _lib;
  late final DartHashFunc _hashData;

  NativeCryptoEngine() {
    _lib = Platform.isWindows
        ? DynamicLibrary.open('crypto_engine.dll')
        : Platform.isMacOS || Platform.isIOS
            ? DynamicLibrary.process()
            : DynamicLibrary.open('libcrypto_engine.so');

    _hashData = _lib
        .lookup<NativeFunction<NativeHashFunc>>('calculate_hash')
        .asFunction<DartHashFunc>();
  }

  int hash(Pointer<Uint8> buffer, int length) => _hashData(buffer, length);
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents