DEV Community

Cover image for How to work javascript file in flutter web ?
Esmaeil Ahmadipour
Esmaeil Ahmadipour

Posted on

How to work javascript file in flutter web ?

One of the capabilities of using flutter for development is creating pwa output. Can we change the final web output (html file) with the commands we wrote in dart? Can we add a tag (like meta or p, …) to the html file with dart commands? You can see how to do this in the following article.

To start, use the default project (counter app) in flutter!

At the top of the main file we add this line:



import 'dart: js' as dartJsFile;



Enter fullscreen mode Exit fullscreen mode

In setState from the _incrementCounter method we add this line:



dartJsFile.context.callMethod ('insertTag');



Enter fullscreen mode Exit fullscreen mode

Now we need to write the JavaScript file. To do this, we need to write the following command in the app terminal:



flutter create.



Enter fullscreen mode Exit fullscreen mode

Add your JavaScript file to the project as shown below:

In the build> web folder ..

In my example , I have to write a method called (insertTag) in my js file that adds new tags inside a tag called (seo). In the file (app .js) I created, I write the method (insertTag):



function insertTag () {
var tag = document.createElement ("meta");
tag.setAttribute ("name", "custom name");
tag.setAttribute ("content", "custom content");
var element = document.getElementById ("seo");
element.appendChild (tag);
}


Enter fullscreen mode Exit fullscreen mode

And in the head of the index .html file, I call it.



<head> <script src = "app.js"> </script> </head>


Enter fullscreen mode Exit fullscreen mode

And inside the body, I define a tag called seo.



<body> <div id = "seo"> </div>



Enter fullscreen mode Exit fullscreen mode

Now, after performing deploy operations on the server or localhost, you can add a new tag to your file (index.html) each time you press the (+) button.

now worked javascript file in flutter web

Top comments (0)