How to asynchronously call JavaScript in Flutter?

Viewed 2552

I have a flutter web where i have a JavaScript function like this:

async function doSomething(value) {
   let x = await something(x);
   return x
}

When I'm now in dart, I have:

final result = await js.context.callMethod('doSomething', ['someValue']));

This returns [object Promise] when I print it, but it does ignore await, does not have a .then function and is therefore not working with promiseToFuture either.

How can I wait for JavaScript to be executed?

4 Answers

Just await doesn't work for js.context.callMethod.

This must be added somewhere in your code, maybe like javascript_controller.dart

@JS()
library script.js;

import 'package:js/js.dart';
import 'dart:js_util';

@JS()
external dynamic doSomething();

and then

Future getSomething(String someValue) async {
  var result = await promiseToFuture(doSomething());
  return result;
}

Maybe use a Future builder to wait for JS to execute?

Future getSomething(String someValue) async {
  var result = await js.context.callMethod('doSomething', [someValue]));
  return result;
}

FutureBuilder(
        future: getSomething(someValue),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var data = snapshot.data;
            print(data);
          } else {
            return Loading();
          }
        }); 

Place it in index.html

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

In Script.js

async function showAlert(href,hashtag,quote) {
      if (response) {   
      window.dartFunc("asd");
      dartFunc("asd");        
      } else if () {
          alert("error adding points");     
      }
      else{
            alert("error dialog close");
      }
  });
};

In your dart file in initstate()

setProperty(window, 'dartFunc', js.allowInterop(dartFunc));

sss() async {
 await js.context.callMethod('showAlert', [
      '',
      '',
      ''
    ]);
}

String dartFunc(String str) {
    Common.showToast('Music');
    Common.showToast(str);

    return 'Inside dartFunc: ' + str;
  }

I tried the same method to do asynchronously from js file using async and used --promisetofuture in dart file but i am unable to wait until we get response from js file for flutter web

async function getPhoneNumber() {
    let res = await someFunction to wait for someTime;
    return res;
}

function somfunc() async{
    var number = await 
    promiseToFuture(js.context.callMethod('getPhoneNumber'));
}
Related