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) {
    alert(message)
}

//you can add more functions here.

In web/index.html, Add script.js

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

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() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  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...