DEV Community

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

Posted on

3

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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more