How to asynchronously call JavaScript in Flutter?

Issue

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?

Solution

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

Answered By – Jackson Lee

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *