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?
You could use dart:js
library to convert the JavaScript Promise to a Dart Future.
import 'dart:async';
import 'dart:js' as js;
Future<dynamic> searchAlgolia(String index, String text) {
final completer = Completer<dynamic>();
js.context.callMethod('asyncTest', [
index,
text,
(result) => completer.complete(result),
(error) => completer.completeError(error),
]);
return completer.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.