How to run JavaScript on Button Click in Flutter Web

In this example, we are going to show you the way to run Javascript (JS) in Flutter Web. It is a simple approach to demonstrate the use of JS or call of JS function on button click in Flutter Web. See the example below for more details.

Creat Script File in web/ folder: script.js

//js function in web/script.js file
function showAlert(message) {

//you can add more functions here.

In web/index.html, Add script.js

  <script src="script.js" defer></script>

In Flutter Web, call showAlert(message) function from main.dart

import 'dart:js' as js; //import dart:js library

js.context.callMethod("showAlert", ["This is alert message"]); //call showAlert with parameter value

Full Dart Code:

import 'package:flutter/material.dart';
import 'dart:js' as js;

void main() {

class MyApp extends StatelessWidget{
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold( 
            appBar: AppBar( 
              title: Text("Call JS Function"),
              backgroundColor: Colors.redAccent,
            body: Container( 
              padding: EdgeInsets.all(20),
              child: Center( 
                child: ElevatedButton(
                  child: Text("Show JS Alert"),
                  onPressed: (){
                      js.context.callMethod("showAlert", ["This is alert message"]);

Output Screenshot:

In this way, you can execute JavaScript from Flutter Web. 

No any Comments on this Article

Please Wait...