Last active
October 11, 2023 18:27
-
-
Save anoop4real/1e4de86f5b1832337169dd9938434d29 to your computer and use it in GitHub Desktop.
WebviewSample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
import 'package:webview_flutter/webview_flutter.dart'; | |
class SimpleWebview extends StatefulWidget { | |
@override | |
_SimpleWebviewState createState() => _SimpleWebviewState(); | |
} | |
class _SimpleWebviewState extends State<SimpleWebview> { | |
WebViewController _controller; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("WebView"), | |
), | |
body: _buildWebView(), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
_controller.evaluateJavascript( | |
'changeImagePathWith("Add your image path here");'); | |
}, | |
child: Icon(Icons.add), | |
backgroundColor: Colors.green, | |
), | |
); | |
} | |
Widget _buildWebView() { | |
return WebView( | |
initialUrl: "about:blank", | |
onWebViewCreated: (WebViewController controller) { | |
_controller = controller; | |
_loadLocalHtmlFile(); | |
}, | |
onPageFinished: (String url) { | |
print('Page finished loading: $url'); | |
}, | |
javascriptMode: JavascriptMode.unrestricted, | |
javascriptChannels: <JavascriptChannel>[ | |
_messageJavascriptChannel(context), | |
_scriptJavascriptChannel(context), | |
].toSet(), | |
); | |
} | |
JavascriptChannel _messageJavascriptChannel(BuildContext context) { | |
return JavascriptChannel( | |
name: 'Print', | |
onMessageReceived: (JavascriptMessage message) { | |
print(message.message); | |
}); | |
} | |
JavascriptChannel _scriptJavascriptChannel(BuildContext context) { | |
return JavascriptChannel( | |
name: 'Postascript', | |
onMessageReceived: (JavascriptMessage message) { | |
// ignore: deprecated_member_use | |
print(message.message); | |
}); | |
} | |
_loadLocalHtmlFile() async { | |
String fileText = await rootBundle.loadString('assets/web/start.html'); | |
_controller.loadUrl(Uri.dataFromString(fileText, | |
mimeType: 'text/html', encoding: Encoding.getByName('utf-8')) | |
.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment