toDelta method
Converts the current HTML string to Quill's Delta format.
This method loads the Quill JavaScript library, initializes a Quill editor with the current HTML content, and retrieves the editor's content in Delta format. A headless in-app WebView is used for this conversion.
Returns:
- A Future that completes with the converted Delta.
Implementation
Future<Delta> toDelta() async {
// Completer to hold the final Delta result.
final Completer<Delta> completer = Completer<Delta>();
// Load the Quill JavaScript library from the specified path.
final String quillJs = await rootBundle.loadString('packages/zds_flutter/lib/assets/js/quill.min.js');
late HeadlessInAppWebView webView;
// Initialize the headless WebView with the loaded Quill library, the current HTML content, and a script to trigger the conversion.
webView = HeadlessInAppWebView(
initialData: InAppWebViewInitialData(
data: '''
<!DOCTYPE html>
<html lang="en">
<head>
<script>$quillJs</script>
</head>
<body>
<div id="editor">
$this
</div>
<script>
var quill = new Quill('#editor', { theme: 'snow' });
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
window.flutter_inappwebview.callHandler('htmlToDelta', ...[JSON.stringify(quill.getContents())]);
});
</script>
</body>
</html>
''',
),
onWebViewCreated: (InAppWebViewController controller) {
// JavaScript handler to retrieve the converted Delta and complete the completer.
controller.addJavaScriptHandler(
handlerName: 'htmlToDelta',
callback: (List<dynamic> args) {
try {
// Dispose the WebView after getting the Delta.
webView.dispose();
// Parse the Delta from the callback arguments.
final dynamic resp = jsonDecode(args.first as String);
// ignore: avoid_dynamic_calls
final Delta delta = Delta.fromJson(resp['ops'] as List<dynamic>);
completer.complete(delta);
} catch (e) {
// Print the error if in debug mode.
if (kDebugMode) print(e);
}
},
);
},
);
await webView.run();
return completer.future;
}