I need to get the search results from Algolia on Flutter Web from JS?
This is in the index.html:
<script>
const client = algoliasearch("4HURXXXXX", "xxxxxb8fxxxx");
async function asyncTest(indexx, text, hitCallback, errorCallback) {
// Get the
const index = client.initIndex(indexx);
const res = await index.search();
return res;
}
</script>
Flutter:
import 'dart:js' as js;
js.context.callMethod('asyncTest', [
'stock_items',
searchValue,
]);
How do I get the Javsdcript promise as a Dart Future?
2
Answers
you could use dart:js library to convert the JavaScript Promise to a Dart Future.
In this piece of code, I created a Completer to convert the JavaScript Promise to a Dart Future. You need to pass the index and text parameters to the asyncTest function in JavaScript. You also pass two callbacks to handle the success and error cases. When the JavaScript Promise resolves, the completer is completed with the result. If the Promise is rejected, the completer is completed with an error. Lastly return the future property of the completer.
You are looking for Darts
promiseToFuture
:Here’s a minmial example, adapt it to your needs:
script.js
main.js
Prints:
Helpful resources
dart:js error when calling promiseToFuture – NoSuchMethodError: tried to call a non-function, such as null: 'jsPromise.then'
What does external mean in Dart?