API Reference
Complete reference of WebF Flutter APIs for controlling WebF instances, managing controllers, and building custom integrations.
Core Classes
WebF
Main widget for displaying WebF apps in your Flutter application.
WebF.fromControllerName(
controllerName: 'app',
loadingWidget: CircularProgressIndicator(),
errorWidget: (error) => Text('Error: $error'),
)WebFController
Controls a WebF instance lifecycle and provides access to the JavaScript runtime.
final controller = WebFController(
onControllerInit: (controller) {
print('Controller initialized');
},
onLoad: (controller) {
print('Content loaded');
},
);WebFControllerManager
Manages multiple WebF controller instances with preloading and prerendering support.
WebFControllerManager.instance.initialize(
WebFControllerManagerConfig(
maxAliveInstances: 5,
maxAttachedInstances: 3,
),
);WebFBundle
Specifies the content source for a WebF controller.
// From URL
WebFBundle.fromUrl('https://example.com/')
// From string content
WebFBundle.fromContent('<html><body>Hello</body></html>')
// From asset
WebFBundle.fromAsset('assets/app.html')WidgetElement
Base class for creating custom Flutter widget elements that can be used from JavaScript.
class MyButton extends WidgetElement {
MyButton(EventTarget? parent) : super(parent);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => dispatchEvent(Event('click')),
child: Text(getAttribute('text') ?? ''),
);
}
}WebFBaseModule
Base class for creating Dart modules that expose native functionality to JavaScript.
class ShareModule extends WebFBaseModule {
ShareModule(ModuleManager manager) : super(manager);
@override
String get name => 'Share';
@override
void dispose() {}
@invokeModule
Future<bool> share(String text) async {
await Share.share(text);
return true;
}
}WebFController Methods
JavaScript Evaluation
// Execute JavaScript code
controller.evaluateJavaScript('console.log("Hello from Flutter")');
// Execute and get return value
final result = await controller.evaluateJavaScript('2 + 2');
print(result); // 4Navigation
// Push new route
controller.hybridHistory.pushState({'userId': 123}, '/profile');
// Go back
controller.hybridHistory.back();
// Replace current route
controller.hybridHistory.replaceState({'page': 'home'}, '/');Reload
// Reload the WebF content
controller.reload();DOM Access
// Get element by ID
final element = controller.view.document.getElementById('myButton');
// Query selector
final elements = controller.view.document.querySelectorAll('.card');Theme Control
// Override dark mode
controller.darkModeOverride = true;
// Reset to automatic
controller.darkModeOverride = null;WebFControllerManager Methods
Get Controller
// Get controller by name (async)
final controller = await WebFControllerManager.instance.getController('app');
// Get controller synchronously (returns null if not ready)
final controller = WebFControllerManager.instance.getControllerSync('app');Add Controllers
// Add with preloading (loads content in background)
await WebFControllerManager.instance.addWithPreload(
name: 'profile',
createController: () => WebFController(),
bundle: WebFBundle.fromUrl('https://example.com/profile'),
);
// Add with prerendering (renders content in background)
await WebFControllerManager.instance.addWithPrerendering(
name: 'home',
createController: () => WebFController(),
bundle: WebFBundle.fromUrl('https://example.com/'),
);Dispose Controller
// Remove and dispose controller
await WebFControllerManager.instance.disposeController('app');Custom Element APIs
Define Custom Element
// Register custom element
WebF.defineCustomElement('my-button', (parent) => MyButton(parent));WidgetElement Methods
// Get attribute
final text = widgetElement.getAttribute('text');
// Set attribute
widgetElement.setAttribute('text', 'Click me');
// Dispatch event
widgetElement.dispatchEvent(Event('click'));
// Listen to attribute changes
@override
void didUpdateWidget() {
final newText = getAttribute('text');
// Update widget state
}Module APIs
Define Module
// Register module
WebF.defineModule((manager) => ShareModule(manager));Invoke Module from JavaScript
// Call module method
const result = await webf.invokeModule('Share', 'share', ['Hello World']);Module Method Annotation
class MyModule extends WebFBaseModule {
@invokeModule
Future<String> myMethod(String param) async {
return 'Result: $param';
}
}Loading State Events
Performance Events
controller.loadingState.onFirstPaint((event) {
print('FP: ${event.elapsed.inMilliseconds}ms');
});
controller.loadingState.onFirstContentfulPaint((event) {
print('FCP: ${event.elapsed.inMilliseconds}ms');
});
controller.loadingState.onLargestContentfulPaint((event) {
print('LCP: ${event.elapsed.inMilliseconds}ms');
});
controller.loadingState.onDOMContentLoaded((event) {
print('DOM ready: ${event.elapsed.inMilliseconds}ms');
});
controller.loadingState.onWindowLoad((event) {
print('Load complete: ${event.elapsed.inMilliseconds}ms');
});Performance Dump
final dump = controller.dumpLoadingState(
options: LoadingStateDumpOptions.html |
LoadingStateDumpOptions.api |
LoadingStateDumpOptions.scripts |
LoadingStateDumpOptions.networkDetailed,
);
print(dump.toStringFiltered());Network Options
Configure HTTP Client
WebFController(
networkOptions: WebFNetworkOptions(
android: WebFNetworkOptions(
httpClientAdapter: () async {
// Return custom Dio adapter
return CronetAdapter(engine);
},
enableHttpCache: true,
),
),
)Cache Control
// Set global cache mode
WebF.setHttpCacheMode(HttpCacheMode.cacheFirst);
// Clear caches
await WebF.clearAllCaches();
// Clear memory cache
HttpCacheController.clearMemoryCache();
// Get cache directory
final cacheDir = await HttpCacheController.getCacheDirectory(
Uri.parse('https://example.com/')
);Callbacks and Hooks
Controller Lifecycle
WebFController(
onControllerInit: (controller) {
// Controller created and initialized
},
onLoad: (controller) {
// Content finished loading
},
onLoadError: (error) {
// Error during loading
},
)LCP Verification
WebFController(
onLCPContentVerification: (contentInfo, routePath) {
print('LCP element: ${contentInfo.tagName}');
print('LCP size: ${contentInfo.width}x${contentInfo.height}');
print('Route: $routePath');
},
)Configuration Options
WebFControllerManagerConfig
WebFControllerManagerConfig(
maxAliveInstances: 5, // Maximum controllers in memory
maxAttachedInstances: 3, // Maximum visible controllers
)LoadingStateDumpOptions
LoadingStateDumpOptions.html // HTML parsing metrics
LoadingStateDumpOptions.api // API call metrics
LoadingStateDumpOptions.scripts // Script execution metrics
LoadingStateDumpOptions.network // Network request summary
LoadingStateDumpOptions.networkDetailed // Detailed network metricsType Definitions
HttpCacheMode
enum HttpCacheMode {
cacheFirst, // Check cache first, then network
networkOnly, // Always use network
cacheOnly, // Only use cache
}Event Types
Custom events that can be dispatched from JavaScript:
// In JavaScript
element.dispatchEvent(new Event('click'));
element.dispatchEvent(new CustomEvent('change', { detail: { value: 'new' } }));// In Dart
widgetElement.addEventListener('click', (event) {
print('Clicked!');
});Next Steps
- Examples - Browse example code
- Performance Monitoring - Monitor app performance
- Build Native Plugins - Create custom modules
External Resources
- API Documentation: https://pub.dev/documentation/webf/latest/
- GitHub Repository: https://github.com/openwebf/webf
- Discord Community: https://discord.gg/DvUBtXZ5rK