javascriptflutterwebviewflutter-inappwebview

flutter inappwebview is not printing on console


i was establishing communication between website and flutter i want to fire message on button click and i have implemented the code below.

 <button onclick="buttonClick()" type="button">Cancel</button>

<script>

        function buttonClick() {

       window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {

             window.flutter_inappwebview.callHandler('cancelbuttonState', 1, true,['msg','CancelbuttonClicked'], {test:'Go-Back'}).then(function(result) {
            
             alert("Hello! Cancel Buttton clicked!!");
              console.log('Hello! Cancel Buttton clicked!!');

             });
           });
          
         }
       </script>

in flutter side i have implemented the following to get the message

controller.addJavaScriptHandler(
                    handlerName: "cancelbuttonState",
                    callback: (args) async {
                      print('Cancel Button clicked');
              
                      return args.reduce((curr, next) => curr + next);
                    });

but both JavaScript and app dint give me console print thanks.


Solution

  • You are executing the below line too late inside the body of the cancel function. You will need to add the listener much earlier for the callback to be registered.

    In other words, you are listening for an event that is already finished.

    window.addEventListener("flutterInAppWebViewPlatformReady" .....
    

    Reorganize your code in a fashion similiar to this:

    <button onclick="buttonClick()" type="button">Cancel</button>
    <script>
        isAppReady = false;
        window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
            isAppReady = true;
        });
        function buttonClick() {
            if (isAppReady) {
                window.flutter_inappwebview.callHandler('cancelbuttonState', 1, true, ['msg', 'CancelbuttonClicked'], { test: 'Go-Back' }).then(function (result) {
                    alert("Hello! Cancel Buttton clicked!!");
                    console.log('Hello! Cancel Buttton clicked!!');
                });
            }
        }
    </script>