How to use flutter webview windows in your flutter application and communicate between them.
Flutter webview is one of the most commonly used library in most applications. But unfortunately, there is no webview plugin that supports all the platform at the time I am writing this post. (let's hope one day you don’t have to read this shitty post)
Promotion: If you are into flutter windows, I have made a course on flutter for windows on udemy, feel free to check out from here
With that said, let's get started with how can we use flutter webview windows in your window application.
Content:
- Add package in yaml
- load URL in web view
- Send/Receive data through flutter
- Send/Receive data through html content
- Complete example to load html content in webview and communicate
Note: adding webview window in my project was’t that easy like other package so make sure you have all the requirement mentioned in package.
This requirement include WebView2 Runtime,SDK Windows 10 1809+ and nuget.exe
Now that you have all the requirements, let's get started with adding the package first.
- Add window webview in your pubspec.yaml file
2. Loading url in webview
You can refer to the official repo example. link provided here
3. Send/Receive data through flutter
We can listen to html content via
// LISTEN DATA FROM HTML CONTENT
_controller.webMessage.listen((event) {
print(event);
});
And send data to html content via
// SENT DATA TO HTML CONTENT
_controller.postWebMessage(json);
4. Send/Receive data through html content
We can listen to flutter via
// LISTEN DATA FROM FLUTTER
window.chrome.webview.addEventListener('message', function(e) {
alert("messagereceived: " + JSON.stringify(e.data));
});
And send data to flutter via
// SEND DATA TO FLUTTER
function sendDataToFlutter() {
var value = {"name":"tashi"}
window.chrome.webview.postMessage(value);
}
5. Load html content in web view and communicate between them
Here is the complete example of working webview content with communication between them
make sure you have html content in the assets folder and the path mentioned in yaml file.
In my case I have test.html and test.js in assets folder
a) Create html file test.html
b) Create js file test.js
c) Now in main.dart:
If you run the app you should be able to load html content and communicate between them.
Let's wrap up. Thanks, guys, I hope you like this shitty blog. please make sure to give a clap 👏 and leave some engagement. let me know in the comment section if you face any issues.
Check out more blogs from CodingWithTashi. Follow me on twitter or Instagram or YouTube.