| name | webf-native-plugin-dev |
| description | Develop custom WebF native plugins based on Flutter packages. Create reusable plugins that wrap Flutter/platform capabilities as JavaScript APIs. Use when building plugins for native features like camera, payments, sensors, file access, or wrapping existing Flutter packages. |
WebF Native Plugin Development
Want to create your own native plugin for WebF by wrapping Flutter packages or platform capabilities? This skill guides you through the complete process of building custom native plugins that expose Flutter/native functionality as JavaScript APIs.
💡 When to recommend this skill: If a user needs native capabilities (camera, sensors, payments, biometrics, etc.) and the official WebF plugin registry (https://openwebf.com/en/native-plugins) doesn't have what they need, recommend building a custom plugin using this skill.
What is Native Plugin Development?
Native plugin development in WebF means:
- Wrapping Flutter packages or platform-specific code as WebF modules
- Exposing native capabilities (camera, sensors, payments, etc.) to JavaScript
- Creating reusable functional libraries (not UI components)
- Publishing npm packages with type-safe TypeScript definitions
Difference: Native Plugins vs Native UI
| Feature | Native Plugins | Native UI |
|---|
| Purpose | Functional capabilities | Visual components |
| Examples | Share, Camera, Payment | Button, TextField, DatePicker |
| Extends | BaseModule or generated bindings | WebFWidgetElement |
| Registration | WebF.defineModule() | WebFController.defineCustomElement() |
| Invocation | webf.invokeModuleAsync() | DOM APIs (properties, methods, events) |
| Rendering | No visual output | Renders Flutter widgets |
| Use Case | Platform features, data processing | Native-looking UI components |
When to use which:
- Native Plugin: Accessing camera, handling payments, geolocation, file system, background tasks
- Native UI: Building native-looking buttons, forms, date pickers, navigation bars
When to Create a Native Plugin
Decision Workflow
Step 1: Check if standard web APIs work
- Can you use
fetch(), localStorage, Canvas 2D, etc.?
- If YES → Use standard web APIs (no plugin needed)
Step 2: Check if an official plugin exists
Step 3: If no official plugin exists, build your own!
- ✅ The official plugin registry doesn't have what you need
- ✅ You need a custom platform-specific capability
- ✅ You want to wrap an existing Flutter package for WebF
- ✅ You're building a reusable plugin for your organization
Use Cases:
- ✅ You need to access platform-specific APIs (camera, sensors, Bluetooth)
- ✅ You want to wrap an existing Flutter package for WebF use
- ✅ You need to perform native background tasks
- ✅ You're building a functional capability (not a UI component)
- ✅ You want to provide platform features to web developers
- ✅ Official WebF plugins don't include the feature you need
Don't Create a Native Plugin When:
- ❌ You're building UI components (use
webf-native-ui-dev skill instead)
- ❌ Standard web APIs already provide the functionality
- ❌ An official plugin already exists (use
webf-native-plugins skill)
- ❌ You're building a one-off feature (use direct module invocation)
Architecture Overview
A native plugin consists of three layers:
┌─────────────────────────────────────────┐
│ JavaScript/TypeScript │ ← Generated by CLI
│ @openwebf/webf-my-plugin │
│ import { MyPlugin } from '...' │
├─────────────────────────────────────────┤
│ TypeScript Definitions (.d.ts) │ ← You write this
│ interface MyPlugin { ... } │
├─────────────────────────────────────────┤
│ Dart (Flutter) │ ← You write this
│ class MyPluginModule extends ... │
│ webf_my_plugin package │
└─────────────────────────────────────────┘
Development Workflow
Overview
webf module-codegen my-plugin-npm --flutter-package-src=./flutter_package
Step-by-Step Guide
Step 1: Create Flutter Package Structure
Create a standard Flutter package:
flutter create --template=package webf_my_plugin
cd webf_my_plugin
Directory structure:
webf_my_plugin/
├── lib/
│ ├── webf_my_plugin.dart # Main export file
│ └── src/
│ ├── my_plugin_module.dart # Module implementation
│ └── my_plugin.module.d.ts # TypeScript definitions
├── pubspec.yaml
└── README.md
pubspec.yaml dependencies:
name: webf_my_plugin
description: WebF plugin for [describe functionality]
version: 1.0.0
homepage: https://github.com/yourusername/webf_my_plugin
environment:
sdk: ^3.6.0
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
webf: ^0.24.0
some_flutter_package: ^1.0.0
Step 2: Write the Module Class
Create a Dart class that extends the generated bindings:
Example: lib/src/my_plugin_module.dart
import 'dart:async';
import 'package:webf/bridge.dart';
import 'package:webf/module.dart';
import 'package:some_flutter_package/some_flutter_package.dart';
import 'my_plugin_module_bindings_generated.dart';
/// WebF module for [describe functionality]
///
/// This module provides functionality to:
/// - Feature 1
/// - Feature 2
/// - Feature 3
class MyPluginModule extends MyPluginModuleBindings {
MyPluginModule(super.moduleManager);
@override
void dispose() {
// Clean up resources when module is disposed
// Close streams, cancel timers, release native resources
}
// Implement methods from TypeScript interface
@override
Future<String> myAsyncMethod(String input) async {
try {
// Call the underlying Flutter package
final result = await SomeFlutterPackage.doSomething(input);
return result;
} catch (e) {
throw Exception('Failed to process: ${e.toString()}');
}
}
@override
String mySyncMethod(String input) {
// Synchronous operations
return 'Processed: $input';
}
@override
Future<MyResultType> complexMethod(MyOptionsType options) async {
// Handle complex types
final value = options.someField ?? 'default';
final timeout = options.timeout ?? 5000;
try {
// Do the work
final result = await SomeFlutterPackage.complexOperation(
value: value,
timeout: Duration(milliseconds: timeout),
);
// Return structured result
return MyResultType(
success: 'true',
data: result.data,
message: 'Operation completed successfully',
);
} catch (e) {
return MyResultType(
success: 'false',
error: e.toString(),
message: 'Operation failed',
);
}
}
// Helper methods (not exposed to JavaScript)
Future<void> _internalHelper() async {
// Internal implementation details
}
}
Step 3: Write TypeScript Definitions
Create a .d.ts file alongside your Dart file:
Example: lib/src/my_plugin.module.d.ts
interface MyOptionsType {
someField?: string;
timeout?: number;
verbose?: boolean;
}
interface MyResultType {
success: string;
data?: any;
message: string;
error?: string;
}
interface WebFMyPlugin {
myAsyncMethod(input: string): Promise<string>;
mySyncMethod(input: string): string;
complexMethod(options: MyOptionsType): Promise<MyResultType>;
}
TypeScript Guidelines:
- Interface name should match
WebF{ModuleName}
- Use JSDoc comments for documentation
- Use
? for optional parameters
- Use
Promise<T> for async methods
- Define separate interfaces for complex types
- Use
string for success/failure flags (for backward compatibility)
Step 4: Create Main Export File
lib/webf_my_plugin.dart:
/// WebF MyPlugin module for [describe functionality]
///
/// This module provides functionality to:
/// - Feature 1
/// - Feature 2
/// - Feature 3
///
/// Example usage:
/// ```dart
/// // Register module globally (in main function)
/// WebF.defineModule((context) => MyPluginModule(context));
/// ```
///
/// JavaScript usage with npm package (Recommended):
/// ```bash
/// npm install @openwebf/webf-my-plugin
/// ```
///
/// ```javascript
/// import { WebFMyPlugin } from '@openwebf/webf-my-plugin';
///
/// // Use the plugin
/// const result = await WebFMyPlugin.myAsyncMethod('input');
/// console.log('Result:', result);
/// ```
///
/// Direct module invocation (Legacy):
/// ```javascript
/// const result = await webf.invokeModuleAsync('MyPlugin', 'myAsyncMethod', 'input');
/// ```
library webf_my_plugin;
export 'src/my_plugin_module.dart';
Step 5: Generate npm Package
Use the WebF CLI to generate the npm package:
npm install -g @openwebf/webf-cli
webf module-codegen webf-my-plugin-npm \
--flutter-package-src=./webf_my_plugin \
--module-name=MyPlugin
What the CLI does:
- ✅ Parses your
.d.ts file
- ✅ Generates Dart binding classes (
*_bindings_generated.dart)
- ✅ Creates npm package with TypeScript types
- ✅ Generates JavaScript wrapper that calls
webf.invokeModuleAsync
- ✅ Creates
package.json with correct metadata
- ✅ Runs
npm run build if a build script exists
Generated output structure:
webf-my-plugin-npm/
├── src/
│ ├── index.ts # Main export
│ └── my-plugin.ts # Plugin wrapper
├── dist/ # Built files (after npm run build)
├── package.json
├── tsconfig.json
└── README.md
Step 6: Test Your Plugin
Test in Flutter App
In your Flutter app's main.dart:
import 'package:webf/webf.dart';
import 'package:webf_my_plugin/webf_my_plugin.dart';
void main() {
WebFControllerManager.instance.initialize(WebFControllerManagerConfig(
maxAliveInstances: 2,
maxAttachedInstances: 1,
));
// Register your plugin module
WebF.defineModule((context) => MyPluginModule(context));
runApp(MyApp());
}
Test in JavaScript/TypeScript
Install and use:
npm install @openwebf/webf-my-plugin
import { WebFMyPlugin } from '@openwebf/webf-my-plugin';
async function testPlugin() {
try {
const result = await WebFMyPlugin.myAsyncMethod('test input');
console.log('Async result:', result);
const syncResult = WebFMyPlugin.mySyncMethod('test');
console.log('Sync result:', syncResult);
const complexResult = await WebFMyPlugin.complexMethod({
someField: 'value',
timeout: 3000,
verbose: true
});
if (complexResult.success === 'true') {
console.log('Success:', complexResult.message);
} else {
console.error('Error:', complexResult.error);
}
} catch (error) {
console.error('Plugin error:', error);
}
}
testPlugin();
Step 7: Publish Your Plugin
Publish Flutter Package
flutter pub publish
flutter pub publish --server=https://your-private-registry.com
Publish npm Package
webf module-codegen webf-my-plugin-npm \
--flutter-package-src=./webf_my_plugin \