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.

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

//you can add more functions here.

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

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

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"]);
                  }),
                ),
            )
        ),
    );
  }
}

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

No any Comments on this Article


Please Wait...