Thursday, June 3, 2021

flutter web

How to call external java script from flutter method?

Step 1: Include javascript in Project\Web\Index.html
Step 2: import 'dart:js' as js;
Step 3:  js.context.callMethod('__javascript function name___', ['function parameters']);


How to listen to javascript event and pass data to flutter?

you can post a message in your js code when the event occurs

window.parent.postMessage('any message', "*");

and listen to it in your dart code

@override
void initState() {
  super.initState();

  //setup listener ---------------------------------
  window.addEventListener("message", (event) {
    MessageEvent event2 = event;
    print(event2.data);
  });
  //------------------------------------------------

}

How to include custom Div with ID in flutter?


Step 1: 
import 'dart:html';
import 'dart:ui' as ui;
Step 2: Call the next widget with expected Div ID

class CustomDiv extends StatelessWidget {
String DivName;
CustomDiv({Key key,String this.DivName }) : super(key: key);

@override
Widget build(BuildContext context) {
final _element = DivElement()
..id = DivName
..innerHtml = 'Hello World from a Div'
..style.width = '400'
..style.height = '200'
..style.backgroundColor='#f7f7f7'
..style.border = '1';

///First create a div and register it
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(DivName, (int viewId) => _element);

return SizedBox(
width: 400,
height: 200,
child: HtmlElementView( viewType: DivName, ));
}
}


How to include normal HTML inside flutter?

use EasyWebView widget

Step 1: in dependencies add easy_web_view: 

Step 2: import 'package:easy_web_view/easy_web_view.dart';

Step 3: Include the widget

class WebViewExample1 extends StatelessWidget {
WebViewExample1({Key key}) : super(key: key);

final ValueKey key1 = ValueKey('key_0');

@override
Widget build(BuildContext context) {

return EasyWebView(
width: 340,
height: 220,
src: htmlContent,
onLoaded: () {
print('Loaded...');
//js.context.callMethod('enableVideo', ['Flutter is calling upon JavaScript!']);

},
isHtml: true,
isMarkdown: false,
convertToWidgets: false,
key: key1,
widgetsTextSelectable: true,
webNavigationDelegate: (_) => WebNavigationDecision.navigate,
crossWindowEvents: [
CrossWindowEvent(
name: 'Test',
eventAction: (eventMessage) {
print('Event message: $eventMessage');
}),
],
// width: 100,
// height: 100,
);
}

String get htmlContent => """
<!DOCTYPE html>
<html>
<head>


</head>
<body bgcolor="#ff0000">
<h1>Hiiiiiiiiiiiiiii</h1>
</body>
</html>
""";

}

No comments: